@ghostpaw/email 0.5.3 → 0.5.5

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.
package/dist/cli.js CHANGED
@@ -11,6 +11,7 @@ import * as net from 'node:net';
11
11
  import * as tls from 'node:tls';
12
12
  import * as zlib from 'node:zlib';
13
13
  import { randomUUID } from 'node:crypto';
14
+ import { isSea } from 'node:sea';
14
15
  import { formatWithOptions } from 'node:util';
15
16
 
16
17
  var __defProp = Object.defineProperty;
@@ -784,7 +785,7 @@ ${e.cyan(d)}
784
785
  var emailVersion;
785
786
  var init_version = __esm({
786
787
  "src/version.ts"() {
787
- emailVersion = "0.5.3";
788
+ emailVersion = "0.5.5";
788
789
  }
789
790
  });
790
791
  function getConfigDir() {
@@ -1212,10 +1213,212 @@ var init_errors2 = __esm({
1212
1213
  }
1213
1214
  });
1214
1215
 
1216
+ // src/surfaces/schema_example.ts
1217
+ function schemaExample(schema, seed = {}) {
1218
+ if (schema.oneOf) {
1219
+ const branch = schema.oneOf.find(
1220
+ (candidate) => Object.entries(seed).every(([key, value]) => {
1221
+ const values = candidate.properties?.[key]?.enum;
1222
+ return !values || values.includes(value);
1223
+ })
1224
+ );
1225
+ return schemaExample({ ...schema, ...branch, oneOf: void 0 }, seed);
1226
+ }
1227
+ if (schema.enum) return schema.enum[0];
1228
+ if (schema.type === "object") {
1229
+ const result = { ...seed };
1230
+ for (const key of schema.required ?? [])
1231
+ if (!(key in result)) {
1232
+ const property = schema.properties?.[key] ?? {};
1233
+ const placeholders = {
1234
+ folder: "INBOX",
1235
+ destination: "Archive",
1236
+ query: "invoice",
1237
+ subject: "Hello",
1238
+ path: "Projects",
1239
+ oldPath: "Projects",
1240
+ newPath: "Archive/Projects"
1241
+ };
1242
+ result[key] = property.type === "string" && !property.enum && placeholders[key] ? placeholders[key] : schemaExample(property);
1243
+ }
1244
+ return result;
1245
+ }
1246
+ if (schema.type === "array") return [schemaExample(schema.items ?? {})];
1247
+ if (schema.type === "integer" || schema.type === "number") return 1;
1248
+ if (schema.type === "boolean") return false;
1249
+ return schema.description?.includes("address") ? "reader@example.com" : "example";
1250
+ }
1251
+ var init_schema_example = __esm({
1252
+ "src/surfaces/schema_example.ts"() {
1253
+ }
1254
+ });
1255
+
1256
+ // src/surfaces/validate_input.ts
1257
+ function validateInput(schema, input, path = "$") {
1258
+ const errors = validate2(schema, input, path);
1259
+ if (path !== "$" || !errors.length) return errors;
1260
+ const seed = {};
1261
+ if (input && typeof input === "object") {
1262
+ for (const key of ["action", "view"])
1263
+ if (schema.properties?.[key]?.enum?.includes(input[key]))
1264
+ seed[key] = input[key];
1265
+ }
1266
+ return errors.map((error) => `${error}; pass ${JSON.stringify(schemaExample(schema, seed))}`);
1267
+ }
1268
+ function validate2(schema, input, path) {
1269
+ const errors = [];
1270
+ const matchesType = (type) => {
1271
+ switch (type) {
1272
+ case "object":
1273
+ return typeof input === "object" && input !== null && !Array.isArray(input);
1274
+ case "array":
1275
+ return Array.isArray(input);
1276
+ case "integer":
1277
+ return typeof input === "number" && Number.isInteger(input);
1278
+ case "number":
1279
+ return typeof input === "number" && Number.isFinite(input);
1280
+ case "null":
1281
+ return input === null;
1282
+ default:
1283
+ return typeof input === type;
1284
+ }
1285
+ };
1286
+ if (schema.type && !(Array.isArray(schema.type) ? schema.type : [schema.type]).some(matchesType)) {
1287
+ return [`${path}: expected ${String(schema.type)}`];
1288
+ }
1289
+ if (schema.enum && !schema.enum.some((value) => JSON.stringify(value) === JSON.stringify(input)))
1290
+ errors.push(`${path}: expected one of ${JSON.stringify(schema.enum)}`);
1291
+ if (schema.oneOf) {
1292
+ const branches = schema.oneOf.map((branch) => validate2(branch, input, path));
1293
+ if (!branches.some((errors2) => errors2.length === 0)) {
1294
+ const record = input && typeof input === "object" ? input : {};
1295
+ const selected = schema.oneOf.findIndex(
1296
+ (branch) => ["action", "view"].some((key) => branch.properties?.[key]?.enum?.includes(record[key]))
1297
+ );
1298
+ errors.push(...branches[selected >= 0 ? selected : 0] ?? []);
1299
+ }
1300
+ }
1301
+ if (typeof input === "object" && input !== null && !Array.isArray(input)) {
1302
+ const record = input;
1303
+ for (const name of schema.required ?? [])
1304
+ if (!Object.hasOwn(record, name)) errors.push(`${path}.${name}: required`);
1305
+ for (const [name, property] of Object.entries(schema.properties ?? {}))
1306
+ if (Object.hasOwn(record, name))
1307
+ errors.push(...validate2(property, record[name], `${path}.${name}`));
1308
+ }
1309
+ if (Array.isArray(input) && schema.items)
1310
+ input.forEach((value, index) => {
1311
+ errors.push(...validate2(schema.items, value, `${path}[${index}]`));
1312
+ });
1313
+ return errors;
1314
+ }
1315
+ var init_validate_input = __esm({
1316
+ "src/surfaces/validate_input.ts"() {
1317
+ init_schema_example();
1318
+ }
1319
+ });
1320
+
1321
+ // src/tools/input_schema.ts
1322
+ function emailInputSchema(name, schema) {
1323
+ const discriminator = name === "mail_read" ? "view" : "action";
1324
+ const actions = schema.properties?.[discriminator]?.enum;
1325
+ if (!actions || name === "mail_sync") return schema;
1326
+ return {
1327
+ ...schema,
1328
+ oneOf: actions.map((value) => {
1329
+ const action = String(value);
1330
+ let required = [];
1331
+ let input;
1332
+ if (name === "mail_read") {
1333
+ if (action === "thread") required = ["threadId"];
1334
+ if (["message", "attachment", "eml"].includes(action)) required = ["folder", "uid"];
1335
+ } else if (name === "mail_compose") {
1336
+ if (action !== "send_draft") {
1337
+ required.push("input");
1338
+ input = {
1339
+ ...payload,
1340
+ required: ["send", "save_draft", "update_draft"].includes(action) ? ["to", "subject"] : action === "forward" ? ["to"] : []
1341
+ };
1342
+ }
1343
+ if (["reply", "forward"].includes(action)) required.push("folder", "uid");
1344
+ if (["update_draft", "send_draft"].includes(action)) required.push("uid");
1345
+ } else if (name === "mail_organize") {
1346
+ required = action === "rename_folder" ? ["oldPath", "newPath"] : action.endsWith("_folder") ? ["path"] : ["folder", "uids"];
1347
+ if (["copy", "move"].includes(action)) required.push("destination");
1348
+ if (action.endsWith("_labels")) required.push("labels");
1349
+ }
1350
+ return {
1351
+ type: "object",
1352
+ required: [...schema.required ?? [], ...required],
1353
+ properties: {
1354
+ ...schema.properties,
1355
+ [discriminator]: { ...schema.properties?.[discriminator], enum: [value] },
1356
+ ...input ? { input } : {}
1357
+ }
1358
+ };
1359
+ })
1360
+ };
1361
+ }
1362
+ var address, recipients, payload;
1363
+ var init_input_schema = __esm({
1364
+ "src/tools/input_schema.ts"() {
1365
+ address = {
1366
+ type: "object",
1367
+ required: ["address"],
1368
+ properties: {
1369
+ address: { type: "string", description: "Email address." },
1370
+ name: { type: "string", description: "Display name." }
1371
+ }
1372
+ };
1373
+ recipients = {
1374
+ type: "array",
1375
+ items: address,
1376
+ description: "Recipient addresses."
1377
+ };
1378
+ payload = {
1379
+ type: "object",
1380
+ properties: {
1381
+ from: address,
1382
+ sender: address,
1383
+ envelopeFrom: address,
1384
+ replyTo: address,
1385
+ to: recipients,
1386
+ cc: recipients,
1387
+ bcc: recipients,
1388
+ subject: { type: "string", description: "Message subject." },
1389
+ text: { type: "string", description: "Plain text body." },
1390
+ html: { type: "string", description: "HTML body." },
1391
+ replyAll: { type: "boolean", description: "Reply to all original recipients." },
1392
+ mode: { type: "string", enum: ["inline", "attachment"] },
1393
+ attachments: {
1394
+ type: "array",
1395
+ description: "Message attachments.",
1396
+ items: {
1397
+ type: "object",
1398
+ required: ["filename", "content"],
1399
+ properties: {
1400
+ filename: { type: "string" },
1401
+ content: { description: "Attachment bytes (Buffer in library calls)." },
1402
+ mimeType: { type: "string" },
1403
+ inline: { type: "boolean" },
1404
+ contentId: { type: "string" }
1405
+ }
1406
+ }
1407
+ },
1408
+ inReplyTo: { type: "string" },
1409
+ references: { type: "array", items: { type: "string" } },
1410
+ headers: { type: "object" }
1411
+ }
1412
+ };
1413
+ }
1414
+ });
1415
+
1215
1416
  // src/tools/email_tools.ts
1216
1417
  var emailTools;
1217
1418
  var init_email_tools = __esm({
1218
1419
  "src/tools/email_tools.ts"() {
1420
+ init_validate_input();
1421
+ init_input_schema();
1219
1422
  emailTools = [
1220
1423
  {
1221
1424
  name: "mail_read",
@@ -1935,6 +2138,21 @@ var init_email_tools = __esm({
1935
2138
  }
1936
2139
  }
1937
2140
  ];
2141
+ for (const tool of emailTools) {
2142
+ Object.assign(tool.inputSchema, emailInputSchema(tool.name, tool.inputSchema));
2143
+ const handler = tool.handler;
2144
+ tool.handler = async (ctx, input) => {
2145
+ const errors = validateInput(tool.inputSchema, input);
2146
+ if (errors.length)
2147
+ return {
2148
+ outcome: "error",
2149
+ summary: errors.join("; "),
2150
+ entities: [],
2151
+ nextSteps: errors
2152
+ };
2153
+ return handler(ctx, input);
2154
+ };
2155
+ }
1938
2156
  }
1939
2157
  });
1940
2158
 
@@ -2233,8 +2451,8 @@ async function authenticate(dispatcher, capabilities, config) {
2233
2451
  }
2234
2452
  if ("mechanism" in config) {
2235
2453
  const { mechanism, credentials } = config;
2236
- const payload = encodeBase64(Buffer.from(JSON.stringify(credentials), "utf8"));
2237
- const res = await dispatcher.execute("AUTHENTICATE", [mechanism, payload]);
2454
+ const payload2 = encodeBase64(Buffer.from(JSON.stringify(credentials), "utf8"));
2455
+ const res = await dispatcher.execute("AUTHENTICATE", [mechanism, payload2]);
2238
2456
  if (res.tagged.status !== "OK") {
2239
2457
  throw new EmailAuthError(`${mechanism} authentication failed`, mechanism);
2240
2458
  }
@@ -3192,23 +3410,23 @@ var init_decode_bodystructure = __esm({
3192
3410
  });
3193
3411
 
3194
3412
  // src/mime/decode_encoded_words.ts
3195
- function decodeQPayload(payload) {
3413
+ function decodeQPayload(payload2) {
3196
3414
  const bytes = [];
3197
- for (let i2 = 0; i2 < payload.length; i2++) {
3198
- const c3 = payload[i2];
3415
+ for (let i2 = 0; i2 < payload2.length; i2++) {
3416
+ const c3 = payload2[i2];
3199
3417
  if (c3 === "_") {
3200
3418
  bytes.push(32);
3201
3419
  continue;
3202
3420
  }
3203
- if (c3 === "=" && i2 + 2 < payload.length) {
3204
- const h2 = payload.slice(i2 + 1, i2 + 3);
3421
+ if (c3 === "=" && i2 + 2 < payload2.length) {
3422
+ const h2 = payload2.slice(i2 + 1, i2 + 3);
3205
3423
  if (/^[0-9A-Fa-f]{2}$/.test(h2)) {
3206
3424
  bytes.push(Number.parseInt(h2, 16));
3207
3425
  i2 += 2;
3208
3426
  continue;
3209
3427
  }
3210
3428
  }
3211
- bytes.push(payload.charCodeAt(i2) & 255);
3429
+ bytes.push(payload2.charCodeAt(i2) & 255);
3212
3430
  }
3213
3431
  return Buffer.from(bytes);
3214
3432
  }
@@ -3279,9 +3497,9 @@ function parseAddressList(items) {
3279
3497
  const mailbox = s3(addrArr[2]);
3280
3498
  const host = s3(addrArr[3]);
3281
3499
  if (!mailbox || !host) continue;
3282
- const address = `${mailbox}@${host}`;
3500
+ const address2 = `${mailbox}@${host}`;
3283
3501
  const name = nameRaw ? decodeEncodedWords(nameRaw) : void 0;
3284
- out.push(name ? { name, address } : { address });
3502
+ out.push(name ? { name, address: address2 } : { address: address2 });
3285
3503
  }
3286
3504
  return out;
3287
3505
  }
@@ -5284,11 +5502,11 @@ function populateFts(db, messageId, textPlain, textHtml) {
5284
5502
  if (!row) return;
5285
5503
  const subject = row.subject != null ? String(row.subject) : "";
5286
5504
  const sender = row.from != null ? String(row.from) : "";
5287
- const recipients = row.to != null ? String(row.to) : "";
5505
+ const recipients2 = row.to != null ? String(row.to) : "";
5288
5506
  db.exec(`DELETE FROM messages_fts WHERE rowid = ${messageId}`);
5289
5507
  db.prepare(
5290
5508
  "INSERT INTO messages_fts(rowid, subject, body_text, sender, recipients) VALUES (?, ?, ?, ?, ?)"
5291
- ).run(messageId, subject, bodyText, sender, recipients);
5509
+ ).run(messageId, subject, bodyText, sender, recipients2);
5292
5510
  }
5293
5511
  var init_fts_populate = __esm({
5294
5512
  "src/sync/fts_populate.ts"() {
@@ -6873,6 +7091,25 @@ var init_write = __esm({
6873
7091
  init_store();
6874
7092
  }
6875
7093
  });
7094
+ function markNpmEntry() {
7095
+ npmEntry = true;
7096
+ }
7097
+ function cliVersion(version, options = {}) {
7098
+ let binary = false;
7099
+ try {
7100
+ binary = (options.isSea ?? isSea)();
7101
+ } catch {
7102
+ }
7103
+ const platform2 = options.platform ?? process.platform;
7104
+ const target = `${platform2 === "win32" ? "windows" : platform2}-${options.arch ?? process.arch}`;
7105
+ return `email ${version} (${binary ? `binary, ${target}` : options.npm ?? npmEntry ? "npm" : "library"})`;
7106
+ }
7107
+ var npmEntry;
7108
+ var init_cli_version = __esm({
7109
+ "src/cli_version.ts"() {
7110
+ npmEntry = false;
7111
+ }
7112
+ });
6876
7113
  function parseCliArgs(argv2, spec) {
6877
7114
  const values = {};
6878
7115
  const positions = [];
@@ -6982,51 +7219,6 @@ var init_cli_args = __esm({
6982
7219
  }
6983
7220
  });
6984
7221
 
6985
- // src/surfaces/validate_input.ts
6986
- function validateInput(schema, input, path = "$") {
6987
- const errors = [];
6988
- const matchesType = (type) => {
6989
- switch (type) {
6990
- case "object":
6991
- return typeof input === "object" && input !== null && !Array.isArray(input);
6992
- case "array":
6993
- return Array.isArray(input);
6994
- case "integer":
6995
- return typeof input === "number" && Number.isInteger(input);
6996
- case "number":
6997
- return typeof input === "number" && Number.isFinite(input);
6998
- case "null":
6999
- return input === null;
7000
- default:
7001
- return typeof input === type;
7002
- }
7003
- };
7004
- if (schema.type && !(Array.isArray(schema.type) ? schema.type : [schema.type]).some(matchesType)) {
7005
- return [`${path}: expected ${String(schema.type)}`];
7006
- }
7007
- if (schema.enum && !schema.enum.some((value) => JSON.stringify(value) === JSON.stringify(input)))
7008
- errors.push(`${path}: expected one of ${JSON.stringify(schema.enum)}`);
7009
- if (schema.oneOf && !schema.oneOf.some((branch) => validateInput(branch, input, path).length === 0))
7010
- errors.push(`${path}: must match at least one schema branch`);
7011
- if (typeof input === "object" && input !== null && !Array.isArray(input)) {
7012
- const record = input;
7013
- for (const name of schema.required ?? [])
7014
- if (!Object.hasOwn(record, name)) errors.push(`${path}.${name}: required`);
7015
- for (const [name, property] of Object.entries(schema.properties ?? {}))
7016
- if (Object.hasOwn(record, name))
7017
- errors.push(...validateInput(property, record[name], `${path}.${name}`));
7018
- }
7019
- if (Array.isArray(input) && schema.items)
7020
- input.forEach((value, index) => {
7021
- errors.push(...validateInput(schema.items, value, `${path}[${index}]`));
7022
- });
7023
- return errors;
7024
- }
7025
- var init_validate_input = __esm({
7026
- "src/surfaces/validate_input.ts"() {
7027
- }
7028
- });
7029
-
7030
7222
  // src/surfaces/cli_commands.ts
7031
7223
  function cliCommands(tools) {
7032
7224
  return tools.flatMap((tool) => {
@@ -7089,14 +7281,14 @@ async function runCliCommand(argv2, options) {
7089
7281
  else if (flag === "--compact") compact = true;
7090
7282
  else if (flag === "--help" || flag === "-h") help = true;
7091
7283
  else if (["--version", "-V", "-v"].includes(flag ?? "")) {
7092
- if (!quiet) stdout2.write(`${options.version}
7284
+ if (!quiet) stdout2.write(`${cliVersion(options.version)}
7093
7285
  `);
7094
7286
  return 0;
7095
7287
  } else if (flag !== "--no-color") continue;
7096
7288
  args.splice(i2--, 1);
7097
7289
  }
7098
7290
  if (args[0] === "version") {
7099
- if (!quiet) stdout2.write(`${options.version}
7291
+ if (!quiet) stdout2.write(`${cliVersion(options.version)}
7100
7292
  `);
7101
7293
  return 0;
7102
7294
  }
@@ -7239,6 +7431,7 @@ ${JSON.stringify(record.data ?? {}, null, 2)}
7239
7431
  }
7240
7432
  var init_cli_commands = __esm({
7241
7433
  "src/surfaces/cli_commands.ts"() {
7434
+ init_cli_version();
7242
7435
  init_cli_args();
7243
7436
  init_validate_input();
7244
7437
  }
@@ -7302,7 +7495,7 @@ ${options.tools.map((tool2) => `${tool2.name} ${tool2.description}`).join("\n")
7302
7495
  return 0;
7303
7496
  }
7304
7497
  if (["--version", "-v"].includes(command)) {
7305
- stdout2.write(`${options.version}
7498
+ stdout2.write(`${cliVersion(options.version)}
7306
7499
  `);
7307
7500
  return 0;
7308
7501
  }
@@ -7320,7 +7513,11 @@ ${options.tools.map((tool2) => `${tool2.name} ${tool2.description}`).join("\n")
7320
7513
  }
7321
7514
  if (command === "skill") {
7322
7515
  if (!options.commands?.skill) return fail("skill command unavailable");
7323
- stdout2.write(await options.commands.skill());
7516
+ try {
7517
+ stdout2.write(await options.commands.skill(args));
7518
+ } catch (error) {
7519
+ return fail(error instanceof Error ? error.message : String(error), 1);
7520
+ }
7324
7521
  return 0;
7325
7522
  }
7326
7523
  if (command === "mcp") {
@@ -7432,472 +7629,315 @@ ${JSON.stringify(tool.inputSchema, null, 2)}
7432
7629
  }
7433
7630
  var init_cli = __esm({
7434
7631
  "src/surfaces/cli.ts"() {
7632
+ init_cli_version();
7435
7633
  init_cli_commands();
7436
7634
  init_surface_types();
7437
7635
  init_validate_input();
7438
7636
  }
7439
7637
  });
7440
7638
 
7441
- // src/surface/email_surface_tools.ts
7442
- var emailMcpTools, emailSurfaceTools;
7443
- var init_email_surface_tools = __esm({
7444
- "src/surface/email_surface_tools.ts"() {
7445
- init_read();
7446
- init_store();
7447
- init_aligned();
7448
- emailMcpTools = emailTools2.map((tool) => ({
7449
- ...tool,
7450
- inputSchema: { ...tool.inputSchema, type: "object" },
7451
- async handler(db, input) {
7452
- const local = tool.name === "mail_search" && input.mode !== "remote" || tool.name === "mail_read" && !input.refresh && input.view !== "eml";
7453
- try {
7454
- if (local) {
7455
- const accountId = listAccounts(db)[0]?.id ?? 1;
7456
- return await tool.handler(
7457
- { read: createReadSurface(db, accountId) },
7458
- input
7459
- );
7460
- }
7461
- const { resolveAccount: resolveAccount2, buildEmailConfig: buildEmailConfig2 } = await Promise.resolve().then(() => (init_account(), account_exports));
7462
- const config = buildEmailConfig2(resolveAccount2());
7463
- const { ImapSession: ImapSession2 } = await Promise.resolve().then(() => (init_session(), session_exports));
7464
- const { createWriteSurface: createWriteSurface2 } = await Promise.resolve().then(() => (init_write(), write_exports));
7465
- const { createNetworkSurface: createNetworkSurface2 } = await Promise.resolve().then(() => (init_network(), network_exports));
7466
- const auth = config.auth;
7467
- const username = "user" in auth ? auth.user : auth.credentials.user ?? auth.credentials.username ?? "user";
7468
- const account = upsertAccount(db, {
7469
- host: config.imap.host,
7470
- port: config.imap.port,
7471
- username
7472
- });
7473
- const session = new ImapSession2(config);
7474
- try {
7475
- const explicitConnect = tool.name === "mail_sync" && ["connect", "reconnect", "disconnect"].includes(String(input.action));
7476
- if (!explicitConnect) await session.connect();
7477
- return await tool.handler(
7478
- {
7479
- read: createReadSurface(db, account.id, { session }),
7480
- write: createWriteSurface2(db, { config, accountId: account.id, session }),
7481
- network: createNetworkSurface2(db, { accountId: account.id, session })
7482
- },
7483
- input
7484
- );
7485
- } finally {
7486
- await session.disconnect();
7487
- }
7488
- } catch (error) {
7489
- return {
7490
- ok: false,
7491
- outcome: "error",
7492
- summary: error instanceof Error ? error.message : String(error),
7493
- next: [
7494
- {
7495
- kind: "use_tool",
7496
- message: "Configure an account with ghostpaw-email account add --name work --imap-host imap.example.com --smtp-host smtp.example.com --user you@example.com --pass yourpassword."
7497
- }
7498
- ],
7499
- data: { entities: [] }
7500
- };
7501
- }
7502
- }
7503
- }));
7504
- emailSurfaceTools = /* @__PURE__ */ emailMcpTools.map(
7505
- (tool) => ({
7506
- ...tool,
7507
- cli: {
7508
- noun: "mail",
7509
- verb: tool.name.slice(5),
7510
- ...tool.name === "mail_search" ? { positionals: ["query"] } : {},
7511
- ...tool.inputSchema.properties?.action?.enum ? {
7512
- action: {
7513
- property: "action",
7514
- verbs: Object.fromEntries(
7515
- tool.inputSchema.properties.action.enum.map((value) => [
7516
- String(value),
7517
- value === "save_draft" ? "draft" : String(value).replaceAll("_", "-")
7518
- ])
7519
- )
7520
- }
7521
- } : {}
7522
- }
7523
- })
7524
- );
7639
+ // src/skills/skill_types.ts
7640
+ function defineEmailSkill(skill) {
7641
+ return skill;
7642
+ }
7643
+ var init_skill_types = __esm({
7644
+ "src/skills/skill_types.ts"() {
7525
7645
  }
7526
7646
  });
7527
7647
 
7528
- // src/surface/open_email_db.ts
7529
- var open_email_db_exports = {};
7530
- __export(open_email_db_exports, {
7531
- openEmailDb: () => openEmailDb
7532
- });
7533
- async function openEmailDb(path) {
7534
- const original = process.emitWarning;
7535
- process.emitWarning = ((warning, ...args) => {
7536
- const type = typeof args[0] === "string" ? args[0] : typeof args[0] === "object" && args[0] !== null && "type" in args[0] ? args[0].type : warning instanceof Error ? warning.name : void 0;
7537
- const message = warning instanceof Error ? warning.message : warning;
7538
- if (type === "ExperimentalWarning" && message.startsWith("SQLite is an experimental feature"))
7539
- return;
7540
- Reflect.apply(original, process, [warning, ...args]);
7541
- });
7542
- let sqlite;
7543
- try {
7544
- sqlite = await import('node:sqlite');
7545
- } finally {
7546
- process.emitWarning = original;
7547
- }
7548
- if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true });
7549
- const db = new sqlite.DatabaseSync(path);
7550
- try {
7551
- db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;");
7552
- const context = db;
7553
- initSchema(context);
7554
- return context;
7555
- } catch (error) {
7556
- db.close();
7557
- throw error;
7558
- }
7559
- }
7560
- var init_open_email_db = __esm({
7561
- "src/surface/open_email_db.ts"() {
7562
- init_schema();
7563
- }
7564
- });
7648
+ // src/skills/cli-guide.ts
7649
+ var cliGuide;
7650
+ var init_cli_guide = __esm({
7651
+ "src/skills/cli-guide.ts"() {
7652
+ init_skill_types();
7653
+ cliGuide = defineEmailSkill({
7654
+ name: "cli",
7655
+ description: "Complete existing email CLI guide.",
7656
+ content: `# SKILL.md \u2014 \`email\` CLI as an Agent Tool Surface
7657
+
7658
+ The \`email\` binary is a local-first email CLI built on top of \`@ghostpaw/email\`. It exposes five
7659
+ intent-shaped commands that map directly to the library's tool layer. Agents invoke it as a
7660
+ subprocess via bash; no MCP server or standing process is needed.
7661
+
7662
+ ---
7663
+
7664
+ ## Prerequisites
7665
+
7666
+ - Node.js \u2265 24
7667
+ - Install once:
7668
+ \`\`\`bash
7669
+ npm install -g @ghostpaw/email # global install, \`email\` in PATH
7670
+ npx @ghostpaw/email account add ... # or zero-install via npx
7671
+ \`\`\`
7672
+
7673
+ ---
7674
+
7675
+ ## Account Setup
7676
+
7677
+ \`\`\`bash
7678
+ email account add \\
7679
+ --name work \\
7680
+ --imap-host imap.fastmail.com --imap-port 993 \\
7681
+ --smtp-host smtp.fastmail.com --smtp-port 587 \\
7682
+ --user me@fastmail.com --pass "app-password"
7683
+
7684
+ email account list # see all accounts
7685
+ email account set-default --name work
7686
+ email account show # shows config (password redacted)
7687
+ \`\`\`
7688
+
7689
+ ### Environment variables (no config file needed \u2014 useful in CI)
7690
+
7691
+ | Variable | Purpose |
7692
+ |---|---|
7693
+ | \`EMAIL_ACCOUNT\` | Select account by slug |
7694
+ | \`EMAIL_IMAP_HOST\` | IMAP hostname |
7695
+ | \`EMAIL_IMAP_PORT\` | IMAP port (default: 993) |
7696
+ | \`EMAIL_IMAP_TLS\` | \`"false"\` to disable TLS |
7697
+ | \`EMAIL_SMTP_HOST\` | SMTP hostname |
7698
+ | \`EMAIL_SMTP_PORT\` | SMTP port (default: 587) |
7699
+ | \`EMAIL_SMTP_TLS\` | \`"false"\` to disable TLS |
7700
+ | \`EMAIL_USER\` | Auth username |
7701
+ | \`EMAIL_PASS\` | Password auth |
7702
+ | \`EMAIL_ACCESS_TOKEN\` | OAuth2 access token |
7703
+ | \`EMAIL_REFRESH_TOKEN\` | OAuth2 refresh token |
7704
+ | \`EMAIL_CONFIG_DIR\` | Override config directory (full path) |
7705
+ | \`EMAIL_DATA_DIR\` | Override SQLite data directory (full path) |
7706
+ | \`NO_COLOR\` | Disable ANSI color output |
7707
+
7708
+ ---
7709
+
7710
+ ## \`--json\` \u2014 Machine-Readable Output
7711
+
7712
+ **Always use \`--json\` when invoking from an agent.** Every command outputs a JSON object:
7713
+
7714
+ \`\`\`json
7715
+ {
7716
+ "outcome": "success",
7717
+ "summary": "42 message(s) in INBOX.",
7718
+ "entities": [
7719
+ { "kind": "message", "id": "1921", "title": "Re: Q2 roadmap" }
7720
+ ],
7721
+ "nextSteps": [
7722
+ "Use view: \\"message\\" with folder and uid to read a specific message."
7723
+ ]
7724
+ }
7725
+ \`\`\`
7726
+
7727
+ \`outcome\` values:
7728
+ - \`"success"\` \u2014 operation completed
7729
+ - \`"no_op"\` \u2014 nothing to do (not an error)
7730
+ - \`"needs_clarification"\` \u2014 more information required; check \`nextSteps\`
7731
+ - \`"error"\` \u2014 operation failed; check \`summary\` for details and \`nextSteps\` for guidance
7732
+
7733
+ **On error, \`--json\` output still goes to stdout** (not stderr) so downstream parsers can always
7734
+ parse stdout unconditionally.
7735
+
7736
+ ---
7737
+
7738
+ ## Exit Codes
7739
+
7740
+ | Code | When |
7741
+ |---|---|
7742
+ | \`0\` | \`success\` or \`no_op\` |
7743
+ | \`1\` | Missing required flag, invalid value, body required |
7744
+ | \`2\` | No config, malformed config, unknown account, no default account |
7745
+ | \`3\` | Authentication failure |
7746
+ | \`4\` | Network / connection failure |
7747
+ | \`5\` | Tool returned \`outcome: "error"\` |
7748
+ | \`6\` | Tool returned \`outcome: "needs_clarification"\` |
7749
+ | \`127\` | Unexpected / unhandled error |
7750
+
7751
+ ---
7752
+
7753
+ ## Commands
7754
+
7755
+ ### \`email read [view]\`
7756
+
7757
+ Read mailbox state. Default view: \`queue\` (INBOX).
7758
+
7759
+ \`\`\`bash
7760
+ email read --json # queue view, INBOX
7761
+ email read folders --json # list all folders
7762
+ email read queue --folder Sent --limit 20 --json
7763
+ email read queue --unread-only --json
7764
+ email read thread --thread-id <id> --json
7765
+ email read message --folder INBOX --uid 1921 --json
7766
+ email read attachment --folder INBOX --uid 1921 --json # list attachments
7767
+ email read eml --folder INBOX --uid 1921 # raw EML bytes to stdout
7768
+ \`\`\`
7769
+
7770
+ **\`eml\` view:** writes raw EML bytes to stdout. In \`--json\` mode the bytes are base64-encoded
7771
+ under a \`"data"\` key.
7772
+
7773
+ \`\`\`bash
7774
+ email read eml --folder INBOX --uid 42 > message.eml
7775
+ email read eml --folder INBOX --uid 42 --json | jq -r '.data' | base64 -d > message.eml
7776
+ \`\`\`
7777
+
7778
+ ### \`email search <query>\`
7779
+
7780
+ Search messages via local FTS5 (default) or remote IMAP SEARCH.
7781
+
7782
+ \`\`\`bash
7783
+ email search "invoice" --json
7784
+ email search "from:boss@work.com subject:quarterly" --json
7785
+ email search "budget 2026" --folder Archive --limit 10 --json
7786
+ email search "urgent" --mode remote --json
7787
+ email search "report" --since 2026-01-01 --before 2026-04-01 --json
7788
+ email search "contract" --has-attachments --json
7789
+ \`\`\`
7790
+
7791
+ ### \`email compose <action>\`
7792
+
7793
+ Compose and send email. Body comes from \`--body\` or piped stdin.
7794
+
7795
+ \`\`\`bash
7796
+ # Send
7797
+ email compose send --to alice@example.com --subject "Hello" --body "Hi there" --json
7798
+ echo "Meeting at 3pm?" | email compose send --to alice@example.com --subject "Quick question"
7565
7799
 
7566
- // src/surface/resolve_email_db_path.ts
7567
- var resolve_email_db_path_exports = {};
7568
- __export(resolve_email_db_path_exports, {
7569
- resolveEmailDbPath: () => resolveEmailDbPath
7570
- });
7571
- function resolveEmailDbPath(options = {}) {
7572
- return options.flag ?? ((options.env ?? process.env).GHOSTPAW_EMAIL_DB || join(homedir(), ".ghostpaw", "email.db"));
7573
- }
7574
- var init_resolve_email_db_path = __esm({
7575
- "src/surface/resolve_email_db_path.ts"() {
7576
- }
7577
- });
7800
+ # Reply (body from stdin)
7801
+ echo "Sounds good!" | email compose reply --folder INBOX --uid 1921
7578
7802
 
7579
- // src/surfaces/mcp_server.ts
7580
- function createMcpServer(options) {
7581
- let initialized = false;
7582
- let context;
7583
- const serverInfo = { name: options.name, version: options.version };
7584
- const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7585
- const error = (id, code, message, data) => ({
7586
- jsonrpc: "2.0",
7587
- id,
7588
- error: { code, message, ...data === void 0 ? {} : { data } }
7589
- });
7590
- const handleMessage = async (msg) => {
7591
- if (!record(msg) || msg.jsonrpc !== "2.0" || typeof msg.method !== "string" || Object.hasOwn(msg, "id") && msg.id !== null && typeof msg.id !== "string" && typeof msg.id !== "number")
7592
- return error(null, -32600, "Invalid Request");
7593
- if (!Object.hasOwn(msg, "id")) return void 0;
7594
- const id = msg.id;
7595
- if (msg.params !== void 0 && !record(msg.params)) return error(id, -32602, "Invalid params");
7596
- const params = record(msg.params) ? msg.params : {};
7597
- const meta = record(params._meta) ? params._meta : {};
7598
- const requested = meta["io.modelcontextprotocol/protocolVersion"];
7599
- const modern = requested !== void 0;
7600
- if (modern && !MCP_SUPPORTED_PROTOCOL_VERSIONS.includes(
7601
- requested
7602
- ))
7603
- return error(id, -32022, "Unsupported protocol version", {
7604
- supported: [...MCP_SUPPORTED_PROTOCOL_VERSIONS],
7605
- requested
7606
- });
7607
- const result = (value) => ({
7608
- jsonrpc: "2.0",
7609
- id,
7610
- result: modern ? {
7611
- ...value,
7612
- resultType: "complete",
7613
- _meta: { "io.modelcontextprotocol/serverInfo": serverInfo }
7614
- } : value
7615
- });
7616
- if (!modern && msg.method === "initialize") {
7617
- initialized = true;
7618
- const version = MCP_SUPPORTED_PROTOCOL_VERSIONS.slice(1).find((v2) => v2 === params.protocolVersion) ?? "2025-11-25";
7619
- return result({
7620
- protocolVersion: version,
7621
- capabilities: { tools: { listChanged: false } },
7622
- serverInfo: { ...serverInfo, ...options.title ? { title: options.title } : {} },
7623
- ...options.instructions ? { instructions: options.instructions } : {}
7624
- });
7625
- }
7626
- if (!modern && !initialized)
7627
- return error(
7628
- id,
7629
- -32602,
7630
- `Protocol version required. Supported versions: ${MCP_SUPPORTED_PROTOCOL_VERSIONS.join(", ")}`
7631
- );
7632
- if (modern && !record(meta["io.modelcontextprotocol/clientCapabilities"]))
7633
- return error(id, -32602, "clientCapabilities must be an object");
7634
- switch (msg.method) {
7635
- case "ping":
7636
- return result({});
7637
- case "server/discover":
7638
- return result({
7639
- supportedVersions: [...MCP_SUPPORTED_PROTOCOL_VERSIONS],
7640
- capabilities: { tools: {} },
7641
- ...options.instructions ? { instructions: options.instructions } : {},
7642
- ttlMs: 6e4,
7643
- cacheScope: "public"
7644
- });
7645
- case "tools/list":
7646
- return result({
7647
- tools: options.tools.map((tool) => ({
7648
- name: tool.name,
7649
- ...tool.title ? { title: tool.title } : {},
7650
- description: tool.description + (tool.whenToUse ? `
7803
+ # Reply-all
7804
+ email compose reply --folder INBOX --uid 1921 --body "Thanks all" --reply-all --json
7651
7805
 
7652
- Use when: ${tool.whenToUse}` : "") + (tool.whenNotToUse ? `
7653
- Not for: ${tool.whenNotToUse}` : ""),
7654
- inputSchema: tool.inputSchema,
7655
- annotations: options.annotations?.(tool) ?? {
7656
- readOnlyHint: tool.readOnly ?? false,
7657
- destructiveHint: !tool.readOnly,
7658
- idempotentHint: tool.readOnly ?? false,
7659
- openWorldHint: false
7660
- }
7661
- })),
7662
- ...modern ? { ttlMs: 6e4, cacheScope: "public" } : {}
7663
- });
7664
- case "tools/call": {
7665
- const tool = options.tools.find((tool2) => tool2.name === params.name);
7666
- if (!tool) return error(id, -32602, `Unknown tool: ${String(params.name)}`);
7667
- const input = params.arguments === void 0 ? {} : params.arguments;
7668
- const errors = validateInput(tool.inputSchema, input);
7669
- if (errors.length)
7670
- return result({ content: [{ type: "text", text: errors.join("\n") }], isError: true });
7671
- try {
7672
- context ??= Promise.resolve().then(options.context);
7673
- const value = await tool.handler(await context, input);
7674
- return result({
7675
- content: [{ type: "text", text: JSON.stringify(value) ?? "null" }],
7676
- ...record(value) ? { structuredContent: value } : {},
7677
- isError: (options.isErrorResult ?? isErrorResult)(value)
7678
- });
7679
- } catch (cause) {
7680
- return result({
7681
- content: [
7682
- { type: "text", text: cause instanceof Error ? cause.message : String(cause) }
7683
- ],
7684
- isError: true
7685
- });
7686
- }
7687
- }
7688
- default:
7689
- return error(id, -32601, "Method not found");
7690
- }
7691
- };
7692
- return {
7693
- handleMessage,
7694
- async handleLine(line) {
7695
- let msg;
7696
- try {
7697
- msg = JSON.parse(line);
7698
- } catch {
7699
- return JSON.stringify(error(null, -32700, "Parse error"));
7700
- }
7701
- const response = await handleMessage(msg);
7702
- return response === void 0 ? void 0 : JSON.stringify(response);
7703
- }
7704
- };
7705
- }
7706
- var MCP_LATEST_PROTOCOL_VERSION, MCP_SUPPORTED_PROTOCOL_VERSIONS;
7707
- var init_mcp_server = __esm({
7708
- "src/surfaces/mcp_server.ts"() {
7709
- init_surface_types();
7710
- init_validate_input();
7711
- MCP_LATEST_PROTOCOL_VERSION = "2026-07-28";
7712
- MCP_SUPPORTED_PROTOCOL_VERSIONS = [
7713
- MCP_LATEST_PROTOCOL_VERSION,
7714
- "2025-11-25",
7715
- "2025-06-18",
7716
- "2025-03-26",
7717
- "2024-11-05"
7718
- ];
7719
- }
7720
- });
7806
+ # Forward
7807
+ email compose forward --folder INBOX --uid 1921 --to bob@example.com --body "FYI" --json
7721
7808
 
7722
- // src/surfaces/mcp_stdio.ts
7723
- async function serveMcpStdio(server, options = {}) {
7724
- const input = options.input ?? process.stdin;
7725
- const output = options.output ?? process.stdout;
7726
- input.setEncoding("utf8");
7727
- let buffer = "";
7728
- const respond = async (line) => {
7729
- if (!line.trim()) return;
7730
- const response = await server.handleLine(line.replace(/\r$/, ""));
7731
- if (response !== void 0)
7732
- await new Promise(
7733
- (resolve, reject) => output.write(`${response}
7734
- `, (error) => error ? reject(error) : resolve())
7735
- );
7736
- };
7737
- for await (const chunk of input) {
7738
- buffer += String(chunk);
7739
- let end = buffer.indexOf("\n");
7740
- while (end !== -1) {
7741
- const line = buffer.slice(0, end);
7742
- buffer = buffer.slice(end + 1);
7743
- await respond(line);
7744
- end = buffer.indexOf("\n");
7745
- }
7746
- }
7747
- await respond(buffer);
7748
- }
7749
- var init_mcp_stdio = __esm({
7750
- "src/surfaces/mcp_stdio.ts"() {
7751
- }
7752
- });
7809
+ # Attach files (comma-separated paths)
7810
+ email compose send --to a@b.com --subject "Report" --body "See attached" \\
7811
+ --attach /path/to/report.pdf,/path/to/data.csv --json
7753
7812
 
7754
- // src/surface/email_mcp_instructions.ts
7755
- var emailMcpInstructions;
7756
- var init_email_mcp_instructions = __esm({
7757
- "src/surface/email_mcp_instructions.ts"() {
7758
- emailMcpInstructions = "Read and search cached email offline. Configure live accounts with email account add before network operations. Inspect messages before replying or changing folders. Confirm recipients and content before sending; trash and folder deletion can remove mail. Credentials use the existing email CLI account configuration or EMAIL_* environment variables.";
7759
- }
7760
- });
7813
+ # Drafts
7814
+ email compose draft --save --to a@b.com --subject "Draft" --body "WIP" --json
7815
+ email compose draft --send-draft 42 --json
7816
+ \`\`\`
7761
7817
 
7762
- // src/surface/email_mcp_options.ts
7763
- function emailMcpOptions(context) {
7764
- return {
7765
- name: "ghostpaw-email",
7766
- version: emailVersion,
7767
- title: "Email",
7768
- instructions: emailMcpInstructions,
7769
- tools: emailMcpTools,
7770
- context,
7771
- annotations: (tool) => ({
7772
- readOnlyHint: tool.readOnly ?? false,
7773
- destructiveHint: ["mail_organize", "mail_compose"].includes(tool.name),
7774
- idempotentHint: tool.readOnly ?? false,
7775
- openWorldHint: true
7776
- })
7777
- };
7778
- }
7779
- var init_email_mcp_options = __esm({
7780
- "src/surface/email_mcp_options.ts"() {
7781
- init_version();
7782
- init_email_mcp_instructions();
7783
- init_email_surface_tools();
7784
- }
7785
- });
7786
-
7787
- // src/surface/serve_email_mcp.ts
7788
- var serve_email_mcp_exports = {};
7789
- __export(serve_email_mcp_exports, {
7790
- serveEmailMcp: () => serveEmailMcp
7791
- });
7792
- async function serveEmailMcp(options = {}) {
7793
- let owned;
7794
- const server = createMcpServer(
7795
- emailMcpOptions(async () => {
7796
- if (options.db) return options.db;
7797
- owned = await openEmailDb(
7798
- resolveEmailDbPath(options.dbPath === void 0 ? {} : { flag: options.dbPath })
7799
- );
7800
- return owned;
7801
- })
7802
- );
7803
- try {
7804
- await serveMcpStdio(server);
7805
- } finally {
7806
- owned?.close();
7807
- }
7808
- }
7809
- var init_serve_email_mcp = __esm({
7810
- "src/surface/serve_email_mcp.ts"() {
7811
- init_mcp_server();
7812
- init_mcp_stdio();
7813
- init_email_mcp_options();
7814
- init_open_email_db();
7815
- init_resolve_email_db_path();
7816
- }
7817
- });
7818
-
7819
- // src/surfaces/skill_markdown.ts
7820
- var skill_markdown_exports = {};
7821
- __export(skill_markdown_exports, {
7822
- renderSkillMarkdown: () => renderSkillMarkdown
7823
- });
7824
- function renderSkillMarkdown(spec, { referencesBase = "references" } = {}) {
7825
- if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(spec.name) || spec.name.length > 64)
7826
- throw new Error("Invalid skill name");
7827
- if (!spec.description.trim() || spec.description.length > 1024 || !spec.description.includes("Use when"))
7828
- throw new Error("Invalid skill description");
7829
- if (spec.compatibility && spec.compatibility.length > 500)
7830
- throw new Error("Invalid compatibility");
7831
- const lines = ["---", `name: ${spec.name}`, `description: ${JSON.stringify(spec.description)}`];
7832
- for (const key of ["license", "compatibility"])
7833
- if (spec[key]) lines.push(`${key}: ${JSON.stringify(spec[key])}`);
7834
- if (spec.metadata) {
7835
- lines.push("metadata:");
7836
- for (const key of Object.keys(spec.metadata).sort())
7837
- lines.push(` ${JSON.stringify(key)}: ${JSON.stringify(spec.metadata[key])}`);
7838
- }
7839
- lines.push(
7840
- "---",
7841
- "",
7842
- `# ${spec.name}`,
7843
- "",
7844
- spec.about,
7845
- "",
7846
- "## Calling tools",
7847
- "",
7848
- `MCP: connect to ${spec.server}, then call a tool by name with its JSON arguments.`,
7849
- "",
7850
- `CLI: \`${spec.bin} call <tool> '<JSON object>'\` or \`${spec.bin} <tool> --parameter value\`${spec.packageName ? ` (without a global install: \`npx -y ${spec.packageName} <tool> ...\`)` : ""}.`,
7851
- "",
7852
- `Inspect schemas with \`${spec.bin} describe <tool>\`. Use \`--db <path>\` to select a database.`,
7853
- ""
7854
- );
7855
- for (const tool of spec.tools) {
7856
- lines.push(
7857
- `## ${tool.name}`,
7858
- "",
7859
- tool.description,
7860
- "",
7861
- `Use when: ${tool.whenToUse ?? ""}`,
7862
- "",
7863
- `Not for: ${tool.whenNotToUse ?? ""}`,
7864
- "",
7865
- tool.readOnly ? "Read-only." : `Writes: ${tool.sideEffects ?? "state"}.`,
7866
- "",
7867
- "| Parameter | Type | Required | Values / description |",
7868
- "| --- | --- | --- | --- |"
7869
- );
7870
- for (const [name, property] of Object.entries(tool.inputSchema.properties ?? {}))
7871
- lines.push(
7872
- `| ${name} | ${property.type ?? property.oneOf?.map((branch) => branch.type).join(" / ") ?? "any"} | ${tool.inputSchema.required?.includes(name) ? "yes" : "no"} | ${(property.enum ? `${property.enum.join(", ")}. ` : "") + (property.description ?? "").replaceAll("|", "\\|").replaceAll("\n", " ")} |`
7873
- );
7874
- lines.push("");
7875
- }
7876
- lines.push(
7877
- "## Workflow guides",
7878
- "",
7879
- ...spec.workflows.map(
7880
- (workflow) => `- [${workflow.name}](${referencesBase}/${workflow.name}.md): ${workflow.description}`
7881
- ),
7882
- "",
7883
- "## Principles",
7884
- "",
7885
- ...spec.principles.map((principle) => `- ${principle}`),
7886
- ""
7887
- );
7888
- return lines.join("\n");
7889
- }
7890
- var init_skill_markdown = __esm({
7891
- "src/surfaces/skill_markdown.ts"() {
7892
- }
7893
- });
7894
-
7895
- // src/skills/skill_types.ts
7896
- function defineEmailSkill(skill) {
7897
- return skill;
7898
- }
7899
- var init_skill_types = __esm({
7900
- "src/skills/skill_types.ts"() {
7818
+ ### \`email organize <action>\`
7819
+
7820
+ Organize messages and folders. \`--uids\` accepts comma-separated UIDs.
7821
+
7822
+ \`\`\`bash
7823
+ email organize mark-read --folder INBOX --uids 1,2,3 --json
7824
+ email organize star --folder INBOX --uids 42 --json
7825
+ email organize archive --folder INBOX --uids 1921,1922 --json
7826
+ email organize trash --folder INBOX --uids 1800 --json
7827
+ email organize move --folder INBOX --uids 100 --destination Archive --json
7828
+ email organize set-labels --folder INBOX --uids 42 --labels "work,priority" --json
7829
+ email organize create-folder --path "Projects/2026" --json
7830
+ email organize rename-folder --old-path "Projects" --new-path "Work/Projects" --json
7831
+ email organize delete-folder --path "OldFolder" --json
7832
+ \`\`\`
7833
+
7834
+ ### \`email sync [action]\`
7835
+
7836
+ Manage IMAP connection and sync local SQLite state. Default action: \`sync\`.
7837
+
7838
+ \`\`\`bash
7839
+ email sync --json # sync all folders (default)
7840
+ email sync sync --folders INBOX,Sent --json
7841
+ email sync sync --bodies all --json # fetch all bodies
7842
+ email sync refresh-folders --json
7843
+ email sync connect --json
7844
+ email sync disconnect --json
7845
+ email sync watch --json # syncs then exits; continuous watching needs the library
7846
+ \`\`\`
7847
+
7848
+ ---
7849
+
7850
+ ## Multi-Step Workflow Examples
7851
+
7852
+ ### Triage inbox
7853
+
7854
+ \`\`\`bash
7855
+ # Get unread messages
7856
+ UNREAD=$(email read queue --unread-only --json)
7857
+ echo "$UNREAD" | jq '.entities[].id'
7858
+
7859
+ # Archive a batch
7860
+ email organize archive --folder INBOX --uids 1,2,3 --json
7861
+ \`\`\`
7862
+
7863
+ ### Read and reply
7864
+
7865
+ \`\`\`bash
7866
+ # Read a specific message
7867
+ MSG=$(email read message --folder INBOX --uid 1921 --json)
7868
+ echo "$MSG" | jq '.summary'
7869
+
7870
+ # Reply
7871
+ echo "Thanks, will do." | email compose reply --folder INBOX --uid 1921 --json
7872
+ \`\`\`
7873
+
7874
+ ### Search and act
7875
+
7876
+ \`\`\`bash
7877
+ # Find all invoices from last month
7878
+ RESULTS=$(email search "invoice" --since 2026-02-01 --before 2026-03-01 --json)
7879
+ UIDS=$(echo "$RESULTS" | jq -r '.entities[].id' | tr '\\n' ',' | sed 's/,$//')
7880
+
7881
+ # Move them to an Archive folder
7882
+ email organize move --folder INBOX --uids "$UIDS" --destination Archive --json
7883
+ \`\`\`
7884
+
7885
+ ### Full sync then read
7886
+
7887
+ \`\`\`bash
7888
+ email sync --json
7889
+ email read queue --limit 20 --json
7890
+ \`\`\`
7891
+
7892
+ ### Export an attachment
7893
+
7894
+ \`\`\`bash
7895
+ # List attachments
7896
+ ATTS=$(email read attachment --folder INBOX --uid 1921 --json)
7897
+ PART=$(echo "$ATTS" | jq -r '.entities[0].id')
7898
+
7899
+ # Download raw bytes
7900
+ email read attachment --folder INBOX --uid 1921 --part-path "$PART" > attachment.pdf
7901
+ \`\`\`
7902
+
7903
+ ---
7904
+
7905
+ ## Error Handling for Agents
7906
+
7907
+ - **Always check \`outcome\`** before acting on \`entities\`. Even exit code 0 can return \`"no_op"\`.
7908
+ - **Do not retry auth errors** (exit 3) \u2014 they require credential changes.
7909
+ - **On \`needs_clarification\`** (exit 6) \u2014 read \`nextSteps\` and ask the user for more information.
7910
+ - **On \`error\`** (exit 5) \u2014 the tool's \`summary\` and \`nextSteps\` contain actionable guidance.
7911
+ - **Network errors** (exit 4) \u2014 retry after a brief pause; check host/port if it persists.
7912
+
7913
+ ---
7914
+
7915
+ ## Piping Patterns
7916
+
7917
+ \`\`\`bash
7918
+ # Pipe body from stdin
7919
+ echo "Hello" | email compose send --to x@y.com --subject "Hi"
7920
+
7921
+ # Export EML and forward to another tool
7922
+ email read eml --folder INBOX --uid 42 | mail -s "fwd" target@example.com
7923
+
7924
+ # JSON pipeline
7925
+ email read queue --json | jq '.entities[] | select(.title | test("invoice"; "i")) | .id'
7926
+
7927
+ # Quiet mode \u2014 only exit code matters
7928
+ email organize archive --folder INBOX --uids 42 --quiet && echo "archived"
7929
+ \`\`\`
7930
+
7931
+ ---
7932
+
7933
+ ## What the CLI Does NOT Do
7934
+
7935
+ - **No persistent daemon.** Every invocation opens a fresh IMAP connection and closes it cleanly.
7936
+ - **No continuous IDLE watch.** \`email sync watch\` syncs once and exits. For push-style updates,
7937
+ use \`Mailbox.network.watch()\` from the library directly.
7938
+ - **No interactive prompts.** All input comes from flags or stdin.
7939
+ `
7940
+ });
7901
7941
  }
7902
7942
  });
7903
7943
 
@@ -8148,115 +8188,621 @@ Failure handling:
8148
8188
  }
8149
8189
  });
8150
8190
 
8151
- // src/skills/search-and-act.ts
8152
- var searchAndActSkill;
8153
- var init_search_and_act = __esm({
8154
- "src/skills/search-and-act.ts"() {
8155
- init_skill_types();
8156
- searchAndActSkill = defineEmailSkill({
8157
- name: "search-and-act",
8158
- description: "Find messages matching criteria (local FTS first, remote IMAP SEARCH as fallback), verify targets, then act \u2014 organize, reply, or present.",
8159
- content: `# Search and Act
8160
-
8161
- Primary tools:
8162
- - \`mail_search\`
8163
- - \`mail_read\`
8164
- - \`mail_organize\`
8165
- - \`mail_compose\`
8166
-
8167
- Steps:
8168
- 1. Start with \`mail_search { query, mode: "local" }\` \u2014 FTS is fast, works offline, and searches subjects, body text, and sender fields simultaneously.
8169
- - Add \`folder\` to restrict to a specific mailbox.
8170
- - Add \`since\` / \`before\` (ISO date strings) to narrow by date range.
8171
- - Add \`hasAttachments: true\` or \`unreadOnly: true\` for quick filters.
8172
- 2. If local results are insufficient (too few hits, or you expect newer unsynced mail), upgrade to \`mail_search { query, mode: "remote", folder }\` to run IMAP SEARCH on the server.
8173
- - Remote search requires an active IMAP session \u2014 run \`mail_sync { action: "connect" }\` first if not connected.
8174
- - Remote search returns UIDs only \u2014 always follow up with \`mail_read { view: "message" }\` to get content.
8175
- 3. Before acting, use \`mail_read { view: "message", folder, uid }\` on the top candidates to confirm the right messages are targeted \u2014 search queries can match multiple threads.
8176
- 4. Decide action based on what you found:
8177
- - Organize \u2192 \`mail_organize\` with the appropriate action (archive, move, star, mark_read, etc.).
8178
- - Reply \u2192 hand off to the \`read-and-reply\` skill.
8179
- - Forward \u2192 \`mail_compose { action: "forward", folder, uid, input }\`.
8180
- - Present only \u2192 return the entity list with subjects and UIDs.
8181
-
8182
- Outcome handling:
8183
- - Empty local results do not mean the mail doesn't exist \u2014 always try remote search before concluding there are no matches.
8184
- - Remote search returns UIDs, not message content; reading before acting is not optional.
8185
- - If both local and remote searches return 0 results, the mail genuinely doesn't exist \u2014 or the query terms are too specific. Try a broader query.
8186
- - FTS queries support stemming and phrase matching; if an exact term fails, try a root word or shorter phrase.
8187
-
8188
- Failure handling:
8189
- - Do not act on search results without reading the target first \u2014 subject-only matches can mislead.
8190
- - Do not run remote search in a loop \u2014 one local attempt and one remote attempt is sufficient before widening or abandoning the query.
8191
- - If \`mode: "remote"\` fails because there is no active session, surface the connection error and suggest \`connect-and-sync\` first.`
8192
- });
8191
+ // src/skills/search-and-act.ts
8192
+ var searchAndActSkill;
8193
+ var init_search_and_act = __esm({
8194
+ "src/skills/search-and-act.ts"() {
8195
+ init_skill_types();
8196
+ searchAndActSkill = defineEmailSkill({
8197
+ name: "search-and-act",
8198
+ description: "Find messages matching criteria (local FTS first, remote IMAP SEARCH as fallback), verify targets, then act \u2014 organize, reply, or present.",
8199
+ content: `# Search and Act
8200
+
8201
+ Primary tools:
8202
+ - \`mail_search\`
8203
+ - \`mail_read\`
8204
+ - \`mail_organize\`
8205
+ - \`mail_compose\`
8206
+
8207
+ Steps:
8208
+ 1. Start with \`mail_search { query, mode: "local" }\` \u2014 FTS is fast, works offline, and searches subjects, body text, and sender fields simultaneously.
8209
+ - Add \`folder\` to restrict to a specific mailbox.
8210
+ - Add \`since\` / \`before\` (ISO date strings) to narrow by date range.
8211
+ - Add \`hasAttachments: true\` or \`unreadOnly: true\` for quick filters.
8212
+ 2. If local results are insufficient (too few hits, or you expect newer unsynced mail), upgrade to \`mail_search { query, mode: "remote", folder }\` to run IMAP SEARCH on the server.
8213
+ - Remote search requires an active IMAP session \u2014 run \`mail_sync { action: "connect" }\` first if not connected.
8214
+ - Remote search returns UIDs only \u2014 always follow up with \`mail_read { view: "message" }\` to get content.
8215
+ 3. Before acting, use \`mail_read { view: "message", folder, uid }\` on the top candidates to confirm the right messages are targeted \u2014 search queries can match multiple threads.
8216
+ 4. Decide action based on what you found:
8217
+ - Organize \u2192 \`mail_organize\` with the appropriate action (archive, move, star, mark_read, etc.).
8218
+ - Reply \u2192 hand off to the \`read-and-reply\` skill.
8219
+ - Forward \u2192 \`mail_compose { action: "forward", folder, uid, input }\`.
8220
+ - Present only \u2192 return the entity list with subjects and UIDs.
8221
+
8222
+ Outcome handling:
8223
+ - Empty local results do not mean the mail doesn't exist \u2014 always try remote search before concluding there are no matches.
8224
+ - Remote search returns UIDs, not message content; reading before acting is not optional.
8225
+ - If both local and remote searches return 0 results, the mail genuinely doesn't exist \u2014 or the query terms are too specific. Try a broader query.
8226
+ - FTS queries support stemming and phrase matching; if an exact term fails, try a root word or shorter phrase.
8227
+
8228
+ Failure handling:
8229
+ - Do not act on search results without reading the target first \u2014 subject-only matches can mislead.
8230
+ - Do not run remote search in a loop \u2014 one local attempt and one remote attempt is sufficient before widening or abandoning the query.
8231
+ - If \`mode: "remote"\` fails because there is no active session, surface the connection error and suggest \`connect-and-sync\` first.`
8232
+ });
8233
+ }
8234
+ });
8235
+
8236
+ // src/skills/triage-inbox.ts
8237
+ var triageInboxSkill;
8238
+ var init_triage_inbox = __esm({
8239
+ "src/skills/triage-inbox.ts"() {
8240
+ init_skill_types();
8241
+ triageInboxSkill = defineEmailSkill({
8242
+ name: "triage-inbox",
8243
+ description: "Process a full inbox from scratch: sync to get latest state, read message queue, selectively fetch bodies for decisions, then bulk-organize by priority.",
8244
+ content: `# Triage Inbox
8245
+
8246
+ Primary tools:
8247
+ - \`mail_sync\`
8248
+ - \`mail_read\`
8249
+ - \`mail_search\`
8250
+ - \`mail_organize\`
8251
+
8252
+ Steps:
8253
+ 1. Use \`mail_sync { action: "sync" }\` first to pull the latest messages. If the account is not connected, run \`mail_sync { action: "connect" }\` before syncing. If offline, skip sync and continue with local state \u2014 note results may be stale.
8254
+ 2. Use \`mail_read { view: "queue", folder: "INBOX", limit: 50 }\` to get the current message list. Add \`unreadOnly: true\` when the inbox is large and only new mail needs attention.
8255
+ 3. Scan subjects and senders from the queue. For messages that need a decision, fetch the full body with \`mail_read { view: "message", folder, uid }\`.
8256
+ 4. For messages that are part of an ongoing thread, use \`mail_read { view: "thread", threadId }\` to see the full conversation before deciding.
8257
+ 5. Categorise each message:
8258
+ - Needs a reply \u2192 hand off to the \`read-and-reply\` skill.
8259
+ - Contains an attachment \u2192 hand off to the \`attachment-workflow\` skill.
8260
+ - Informational / done \u2192 \`mail_organize { action: "archive", folder, uids }\`.
8261
+ - Spam / junk \u2192 \`mail_organize { action: "junk", folder, uids }\`.
8262
+ - Important but deferred \u2192 \`mail_organize { action: "star", folder, uids }\`.
8263
+ 6. Apply bulk flag operations before disposition: \`mark_read\` first, then \`archive\`/\`trash\`/\`move\` in separate calls.
8264
+
8265
+ Outcome handling:
8266
+ - If sync returns \`totalNew: 0\`, the inbox is already current \u2014 proceed directly to the queue read.
8267
+ - If a message body fetch is slow or fails, it means the body is not yet cached \u2014 run \`mail_sync { action: "sync" }\` with the specific folder, then retry.
8268
+ - If a thread has many messages, read only the most recent before deciding; fetch earlier messages only when context is explicitly needed.
8269
+
8270
+ Failure handling:
8271
+ - Do not archive without reading when the message is from a known sender with an active thread.
8272
+ - Do not bulk-trash without confirming the source folder is correct \u2014 junk detection and legit mail can look similar.
8273
+ - Do not triage in one pass if the inbox has more than 50 messages \u2014 paginate with \`limit\` and \`offset\` to avoid missing messages.`
8274
+ });
8275
+ }
8276
+ });
8277
+
8278
+ // src/skills/email_skills.ts
8279
+ var emailSkills;
8280
+ var init_email_skills = __esm({
8281
+ "src/skills/email_skills.ts"() {
8282
+ init_attachment_workflow();
8283
+ init_compose_and_send();
8284
+ init_connect_and_sync();
8285
+ init_organize_bulk();
8286
+ init_read_and_reply();
8287
+ init_recover_from_disruption();
8288
+ init_search_and_act();
8289
+ init_triage_inbox();
8290
+ emailSkills = [
8291
+ triageInboxSkill,
8292
+ readAndReplySkill,
8293
+ connectAndSyncSkill,
8294
+ searchAndActSkill,
8295
+ composeAndSendSkill,
8296
+ organizeBulkSkill,
8297
+ attachmentWorkflowSkill,
8298
+ recoverFromDisruptionSkill
8299
+ ];
8300
+ }
8301
+ });
8302
+
8303
+ // src/surface/email_surface_tools.ts
8304
+ var emailMcpTools, emailSurfaceTools;
8305
+ var init_email_surface_tools = __esm({
8306
+ "src/surface/email_surface_tools.ts"() {
8307
+ init_read();
8308
+ init_store();
8309
+ init_aligned();
8310
+ emailMcpTools = emailTools2.map((tool) => ({
8311
+ ...tool,
8312
+ inputSchema: { ...tool.inputSchema, type: "object" },
8313
+ async handler(db, input) {
8314
+ const local = tool.name === "mail_search" && input.mode !== "remote" || tool.name === "mail_read" && !input.refresh && input.view !== "eml";
8315
+ try {
8316
+ if (local) {
8317
+ const accountId = listAccounts(db)[0]?.id ?? 1;
8318
+ return await tool.handler(
8319
+ { read: createReadSurface(db, accountId) },
8320
+ input
8321
+ );
8322
+ }
8323
+ const { resolveAccount: resolveAccount2, buildEmailConfig: buildEmailConfig2 } = await Promise.resolve().then(() => (init_account(), account_exports));
8324
+ const config = buildEmailConfig2(resolveAccount2());
8325
+ const { ImapSession: ImapSession2 } = await Promise.resolve().then(() => (init_session(), session_exports));
8326
+ const { createWriteSurface: createWriteSurface2 } = await Promise.resolve().then(() => (init_write(), write_exports));
8327
+ const { createNetworkSurface: createNetworkSurface2 } = await Promise.resolve().then(() => (init_network(), network_exports));
8328
+ const auth = config.auth;
8329
+ const username = "user" in auth ? auth.user : auth.credentials.user ?? auth.credentials.username ?? "user";
8330
+ const account = upsertAccount(db, {
8331
+ host: config.imap.host,
8332
+ port: config.imap.port,
8333
+ username
8334
+ });
8335
+ const session = new ImapSession2(config);
8336
+ try {
8337
+ const explicitConnect = tool.name === "mail_sync" && ["connect", "reconnect", "disconnect"].includes(String(input.action));
8338
+ if (!explicitConnect) await session.connect();
8339
+ return await tool.handler(
8340
+ {
8341
+ read: createReadSurface(db, account.id, { session }),
8342
+ write: createWriteSurface2(db, { config, accountId: account.id, session }),
8343
+ network: createNetworkSurface2(db, { accountId: account.id, session })
8344
+ },
8345
+ input
8346
+ );
8347
+ } finally {
8348
+ await session.disconnect();
8349
+ }
8350
+ } catch (error) {
8351
+ return {
8352
+ ok: false,
8353
+ outcome: "error",
8354
+ summary: error instanceof Error ? error.message : String(error),
8355
+ next: [
8356
+ {
8357
+ kind: "use_tool",
8358
+ message: "Configure an account with ghostpaw-email account add --name work --imap-host imap.example.com --smtp-host smtp.example.com --user you@example.com --pass yourpassword."
8359
+ }
8360
+ ],
8361
+ data: { entities: [] }
8362
+ };
8363
+ }
8364
+ }
8365
+ }));
8366
+ emailSurfaceTools = /* @__PURE__ */ emailMcpTools.map(
8367
+ (tool) => ({
8368
+ ...tool,
8369
+ cli: {
8370
+ noun: "mail",
8371
+ verb: tool.name.slice(5),
8372
+ ...tool.name === "mail_search" ? { positionals: ["query"] } : {},
8373
+ ...tool.inputSchema.properties?.action?.enum ? {
8374
+ action: {
8375
+ property: "action",
8376
+ verbs: Object.fromEntries(
8377
+ tool.inputSchema.properties.action.enum.map((value) => [
8378
+ String(value),
8379
+ value === "save_draft" ? "draft" : String(value).replaceAll("_", "-")
8380
+ ])
8381
+ )
8382
+ }
8383
+ } : {}
8384
+ }
8385
+ })
8386
+ );
8387
+ }
8388
+ });
8389
+
8390
+ // src/surface/open_email_db.ts
8391
+ var open_email_db_exports = {};
8392
+ __export(open_email_db_exports, {
8393
+ openEmailDb: () => openEmailDb
8394
+ });
8395
+ async function openEmailDb(path) {
8396
+ const original = process.emitWarning;
8397
+ process.emitWarning = ((warning, ...args) => {
8398
+ const type = typeof args[0] === "string" ? args[0] : typeof args[0] === "object" && args[0] !== null && "type" in args[0] ? args[0].type : warning instanceof Error ? warning.name : void 0;
8399
+ const message = warning instanceof Error ? warning.message : warning;
8400
+ if (type === "ExperimentalWarning" && message.startsWith("SQLite is an experimental feature"))
8401
+ return;
8402
+ Reflect.apply(original, process, [warning, ...args]);
8403
+ });
8404
+ let sqlite;
8405
+ try {
8406
+ sqlite = await import('node:sqlite');
8407
+ } finally {
8408
+ process.emitWarning = original;
8409
+ }
8410
+ if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true });
8411
+ const db = new sqlite.DatabaseSync(path);
8412
+ try {
8413
+ db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;");
8414
+ const context = db;
8415
+ initSchema(context);
8416
+ return context;
8417
+ } catch (error) {
8418
+ db.close();
8419
+ throw error;
8420
+ }
8421
+ }
8422
+ var init_open_email_db = __esm({
8423
+ "src/surface/open_email_db.ts"() {
8424
+ init_schema();
8425
+ }
8426
+ });
8427
+
8428
+ // src/surface/resolve_email_db_path.ts
8429
+ var resolve_email_db_path_exports = {};
8430
+ __export(resolve_email_db_path_exports, {
8431
+ resolveEmailDbPath: () => resolveEmailDbPath
8432
+ });
8433
+ function resolveEmailDbPath(options = {}) {
8434
+ return options.flag ?? ((options.env ?? process.env).GHOSTPAW_EMAIL_DB || join(homedir(), ".ghostpaw", "email.db"));
8435
+ }
8436
+ var init_resolve_email_db_path = __esm({
8437
+ "src/surface/resolve_email_db_path.ts"() {
8438
+ }
8439
+ });
8440
+
8441
+ // src/surfaces/mcp_server.ts
8442
+ function createMcpServer(options) {
8443
+ let initialized = false;
8444
+ let context;
8445
+ const serverInfo = { name: options.name, version: options.version };
8446
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8447
+ const error = (id, code, message, data) => ({
8448
+ jsonrpc: "2.0",
8449
+ id,
8450
+ error: { code, message, ...data === void 0 ? {} : { data } }
8451
+ });
8452
+ const handleMessage = async (msg) => {
8453
+ if (!record(msg) || msg.jsonrpc !== "2.0" || typeof msg.method !== "string" || Object.hasOwn(msg, "id") && msg.id !== null && typeof msg.id !== "string" && typeof msg.id !== "number")
8454
+ return error(null, -32600, "Invalid Request");
8455
+ if (!Object.hasOwn(msg, "id")) return void 0;
8456
+ const id = msg.id;
8457
+ if (msg.params !== void 0 && !record(msg.params)) return error(id, -32602, "Invalid params");
8458
+ const params = record(msg.params) ? msg.params : {};
8459
+ const meta = record(params._meta) ? params._meta : {};
8460
+ const requested = meta["io.modelcontextprotocol/protocolVersion"];
8461
+ const modern = requested !== void 0;
8462
+ if (modern && !MCP_SUPPORTED_PROTOCOL_VERSIONS.includes(
8463
+ requested
8464
+ ))
8465
+ return error(id, -32022, "Unsupported protocol version", {
8466
+ supported: [...MCP_SUPPORTED_PROTOCOL_VERSIONS],
8467
+ requested
8468
+ });
8469
+ const result = (value) => ({
8470
+ jsonrpc: "2.0",
8471
+ id,
8472
+ result: modern ? {
8473
+ ...value,
8474
+ resultType: "complete",
8475
+ _meta: { "io.modelcontextprotocol/serverInfo": serverInfo }
8476
+ } : value
8477
+ });
8478
+ if (!modern && msg.method === "initialize") {
8479
+ initialized = true;
8480
+ const version = MCP_SUPPORTED_PROTOCOL_VERSIONS.slice(1).find((v2) => v2 === params.protocolVersion) ?? "2025-11-25";
8481
+ return result({
8482
+ protocolVersion: version,
8483
+ capabilities: { tools: { listChanged: false } },
8484
+ serverInfo: { ...serverInfo, ...options.title ? { title: options.title } : {} },
8485
+ ...options.instructions ? { instructions: options.instructions } : {}
8486
+ });
8487
+ }
8488
+ if (!modern && !initialized)
8489
+ return error(
8490
+ id,
8491
+ -32602,
8492
+ `Protocol version required. Supported versions: ${MCP_SUPPORTED_PROTOCOL_VERSIONS.join(", ")}`
8493
+ );
8494
+ if (modern && !record(meta["io.modelcontextprotocol/clientCapabilities"]))
8495
+ return error(id, -32602, "clientCapabilities must be an object");
8496
+ switch (msg.method) {
8497
+ case "ping":
8498
+ return result({});
8499
+ case "server/discover":
8500
+ return result({
8501
+ supportedVersions: [...MCP_SUPPORTED_PROTOCOL_VERSIONS],
8502
+ capabilities: { tools: {} },
8503
+ ...options.instructions ? { instructions: options.instructions } : {},
8504
+ ttlMs: 6e4,
8505
+ cacheScope: "public"
8506
+ });
8507
+ case "tools/list":
8508
+ return result({
8509
+ tools: options.tools.map((tool) => ({
8510
+ name: tool.name,
8511
+ ...tool.title ? { title: tool.title } : {},
8512
+ description: tool.description + (tool.whenToUse ? `
8513
+
8514
+ Use when: ${tool.whenToUse}` : "") + (tool.whenNotToUse ? `
8515
+ Not for: ${tool.whenNotToUse}` : ""),
8516
+ inputSchema: tool.inputSchema,
8517
+ annotations: options.annotations?.(tool) ?? {
8518
+ readOnlyHint: tool.readOnly ?? false,
8519
+ destructiveHint: !tool.readOnly,
8520
+ idempotentHint: tool.readOnly ?? false,
8521
+ openWorldHint: false
8522
+ }
8523
+ })),
8524
+ ...modern ? { ttlMs: 6e4, cacheScope: "public" } : {}
8525
+ });
8526
+ case "tools/call": {
8527
+ const tool = options.tools.find((tool2) => tool2.name === params.name);
8528
+ if (!tool) return error(id, -32602, `Unknown tool: ${String(params.name)}`);
8529
+ const input = params.arguments === void 0 ? {} : params.arguments;
8530
+ const errors = validateInput(tool.inputSchema, input);
8531
+ if (errors.length)
8532
+ return result({ content: [{ type: "text", text: errors.join("\n") }], isError: true });
8533
+ try {
8534
+ context ??= Promise.resolve().then(options.context);
8535
+ const value = await tool.handler(await context, input);
8536
+ return result({
8537
+ content: [{ type: "text", text: JSON.stringify(value) ?? "null" }],
8538
+ ...record(value) ? { structuredContent: value } : {},
8539
+ isError: (options.isErrorResult ?? isErrorResult)(value)
8540
+ });
8541
+ } catch (cause) {
8542
+ return result({
8543
+ content: [
8544
+ { type: "text", text: cause instanceof Error ? cause.message : String(cause) }
8545
+ ],
8546
+ isError: true
8547
+ });
8548
+ }
8549
+ }
8550
+ default:
8551
+ return error(id, -32601, "Method not found");
8552
+ }
8553
+ };
8554
+ return {
8555
+ handleMessage,
8556
+ async handleLine(line) {
8557
+ let msg;
8558
+ try {
8559
+ msg = JSON.parse(line);
8560
+ } catch {
8561
+ return JSON.stringify(error(null, -32700, "Parse error"));
8562
+ }
8563
+ const response = await handleMessage(msg);
8564
+ return response === void 0 ? void 0 : JSON.stringify(response);
8565
+ }
8566
+ };
8567
+ }
8568
+ var MCP_LATEST_PROTOCOL_VERSION, MCP_SUPPORTED_PROTOCOL_VERSIONS;
8569
+ var init_mcp_server = __esm({
8570
+ "src/surfaces/mcp_server.ts"() {
8571
+ init_surface_types();
8572
+ init_validate_input();
8573
+ MCP_LATEST_PROTOCOL_VERSION = "2026-07-28";
8574
+ MCP_SUPPORTED_PROTOCOL_VERSIONS = [
8575
+ MCP_LATEST_PROTOCOL_VERSION,
8576
+ "2025-11-25",
8577
+ "2025-06-18",
8578
+ "2025-03-26",
8579
+ "2024-11-05"
8580
+ ];
8581
+ }
8582
+ });
8583
+
8584
+ // src/surfaces/mcp_stdio.ts
8585
+ async function serveMcpStdio(server, options = {}) {
8586
+ const input = options.input ?? process.stdin;
8587
+ const output = options.output ?? process.stdout;
8588
+ input.setEncoding("utf8");
8589
+ let buffer = "";
8590
+ const respond = async (line) => {
8591
+ if (!line.trim()) return;
8592
+ const response = await server.handleLine(line.replace(/\r$/, ""));
8593
+ if (response !== void 0)
8594
+ await new Promise(
8595
+ (resolve, reject) => output.write(`${response}
8596
+ `, (error) => error ? reject(error) : resolve())
8597
+ );
8598
+ };
8599
+ for await (const chunk of input) {
8600
+ buffer += String(chunk);
8601
+ let end = buffer.indexOf("\n");
8602
+ while (end !== -1) {
8603
+ const line = buffer.slice(0, end);
8604
+ buffer = buffer.slice(end + 1);
8605
+ await respond(line);
8606
+ end = buffer.indexOf("\n");
8607
+ }
8608
+ }
8609
+ await respond(buffer);
8610
+ }
8611
+ var init_mcp_stdio = __esm({
8612
+ "src/surfaces/mcp_stdio.ts"() {
8613
+ }
8614
+ });
8615
+
8616
+ // src/surface/email_mcp_instructions.ts
8617
+ var emailMcpInstructions;
8618
+ var init_email_mcp_instructions = __esm({
8619
+ "src/surface/email_mcp_instructions.ts"() {
8620
+ emailMcpInstructions = "Read and search cached email offline. Configure live accounts with email account add before network operations. Inspect messages before replying or changing folders. Confirm recipients and content before sending; trash and folder deletion can remove mail. Credentials use the existing email CLI account configuration or EMAIL_* environment variables.";
8193
8621
  }
8194
8622
  });
8195
8623
 
8196
- // src/skills/triage-inbox.ts
8197
- var triageInboxSkill;
8198
- var init_triage_inbox = __esm({
8199
- "src/skills/triage-inbox.ts"() {
8200
- init_skill_types();
8201
- triageInboxSkill = defineEmailSkill({
8202
- name: "triage-inbox",
8203
- description: "Process a full inbox from scratch: sync to get latest state, read message queue, selectively fetch bodies for decisions, then bulk-organize by priority.",
8204
- content: `# Triage Inbox
8205
-
8206
- Primary tools:
8207
- - \`mail_sync\`
8208
- - \`mail_read\`
8209
- - \`mail_search\`
8210
- - \`mail_organize\`
8211
-
8212
- Steps:
8213
- 1. Use \`mail_sync { action: "sync" }\` first to pull the latest messages. If the account is not connected, run \`mail_sync { action: "connect" }\` before syncing. If offline, skip sync and continue with local state \u2014 note results may be stale.
8214
- 2. Use \`mail_read { view: "queue", folder: "INBOX", limit: 50 }\` to get the current message list. Add \`unreadOnly: true\` when the inbox is large and only new mail needs attention.
8215
- 3. Scan subjects and senders from the queue. For messages that need a decision, fetch the full body with \`mail_read { view: "message", folder, uid }\`.
8216
- 4. For messages that are part of an ongoing thread, use \`mail_read { view: "thread", threadId }\` to see the full conversation before deciding.
8217
- 5. Categorise each message:
8218
- - Needs a reply \u2192 hand off to the \`read-and-reply\` skill.
8219
- - Contains an attachment \u2192 hand off to the \`attachment-workflow\` skill.
8220
- - Informational / done \u2192 \`mail_organize { action: "archive", folder, uids }\`.
8221
- - Spam / junk \u2192 \`mail_organize { action: "junk", folder, uids }\`.
8222
- - Important but deferred \u2192 \`mail_organize { action: "star", folder, uids }\`.
8223
- 6. Apply bulk flag operations before disposition: \`mark_read\` first, then \`archive\`/\`trash\`/\`move\` in separate calls.
8224
-
8225
- Outcome handling:
8226
- - If sync returns \`totalNew: 0\`, the inbox is already current \u2014 proceed directly to the queue read.
8227
- - If a message body fetch is slow or fails, it means the body is not yet cached \u2014 run \`mail_sync { action: "sync" }\` with the specific folder, then retry.
8228
- - If a thread has many messages, read only the most recent before deciding; fetch earlier messages only when context is explicitly needed.
8624
+ // src/surface/email_mcp_options.ts
8625
+ function emailMcpOptions(context) {
8626
+ return {
8627
+ name: "ghostpaw-email",
8628
+ version: emailVersion,
8629
+ title: "Email",
8630
+ instructions: emailMcpInstructions,
8631
+ tools: emailMcpTools,
8632
+ context,
8633
+ annotations: (tool) => ({
8634
+ readOnlyHint: tool.readOnly ?? false,
8635
+ destructiveHint: ["mail_organize", "mail_compose"].includes(tool.name),
8636
+ idempotentHint: tool.readOnly ?? false,
8637
+ openWorldHint: true
8638
+ })
8639
+ };
8640
+ }
8641
+ var init_email_mcp_options = __esm({
8642
+ "src/surface/email_mcp_options.ts"() {
8643
+ init_version();
8644
+ init_email_mcp_instructions();
8645
+ init_email_surface_tools();
8646
+ }
8647
+ });
8229
8648
 
8230
- Failure handling:
8231
- - Do not archive without reading when the message is from a known sender with an active thread.
8232
- - Do not bulk-trash without confirming the source folder is correct \u2014 junk detection and legit mail can look similar.
8233
- - Do not triage in one pass if the inbox has more than 50 messages \u2014 paginate with \`limit\` and \`offset\` to avoid missing messages.`
8234
- });
8649
+ // src/surface/serve_email_mcp.ts
8650
+ var serve_email_mcp_exports = {};
8651
+ __export(serve_email_mcp_exports, {
8652
+ serveEmailMcp: () => serveEmailMcp
8653
+ });
8654
+ async function serveEmailMcp(options = {}) {
8655
+ let owned;
8656
+ const server = createMcpServer(
8657
+ emailMcpOptions(async () => {
8658
+ if (options.db) return options.db;
8659
+ owned = await openEmailDb(
8660
+ resolveEmailDbPath(options.dbPath === void 0 ? {} : { flag: options.dbPath })
8661
+ );
8662
+ return owned;
8663
+ })
8664
+ );
8665
+ try {
8666
+ await serveMcpStdio(server);
8667
+ } finally {
8668
+ owned?.close();
8669
+ }
8670
+ }
8671
+ var init_serve_email_mcp = __esm({
8672
+ "src/surface/serve_email_mcp.ts"() {
8673
+ init_mcp_server();
8674
+ init_mcp_stdio();
8675
+ init_email_mcp_options();
8676
+ init_open_email_db();
8677
+ init_resolve_email_db_path();
8235
8678
  }
8236
8679
  });
8237
8680
 
8238
- // src/skills/email_skills.ts
8239
- var emailSkills;
8240
- var init_email_skills = __esm({
8241
- "src/skills/email_skills.ts"() {
8242
- init_attachment_workflow();
8243
- init_compose_and_send();
8244
- init_connect_and_sync();
8245
- init_organize_bulk();
8246
- init_read_and_reply();
8247
- init_recover_from_disruption();
8248
- init_search_and_act();
8249
- init_triage_inbox();
8250
- emailSkills = [
8251
- triageInboxSkill,
8252
- readAndReplySkill,
8253
- connectAndSyncSkill,
8254
- searchAndActSkill,
8255
- composeAndSendSkill,
8256
- organizeBulkSkill,
8257
- attachmentWorkflowSkill,
8258
- recoverFromDisruptionSkill
8259
- ];
8681
+ // src/surfaces/skill_markdown.ts
8682
+ var skill_markdown_exports = {};
8683
+ __export(skill_markdown_exports, {
8684
+ renderSkillMarkdown: () => renderSkillMarkdown
8685
+ });
8686
+ function renderSkillMarkdown(spec, { referencesBase = "references" } = {}) {
8687
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(spec.name) || spec.name.length > 64)
8688
+ throw new Error("Invalid skill name");
8689
+ if (!spec.description.trim() || spec.description.length > 1024 || !spec.description.includes("Use when"))
8690
+ throw new Error("Invalid skill description");
8691
+ if (spec.compatibility && spec.compatibility.length > 500)
8692
+ throw new Error("Invalid compatibility");
8693
+ const lines = ["---", `name: ${spec.name}`, `description: ${JSON.stringify(spec.description)}`];
8694
+ for (const key of ["license", "compatibility"])
8695
+ if (spec[key]) lines.push(`${key}: ${JSON.stringify(spec[key])}`);
8696
+ if (spec.metadata) {
8697
+ lines.push("metadata:");
8698
+ for (const key of Object.keys(spec.metadata).sort())
8699
+ lines.push(` ${JSON.stringify(key)}: ${JSON.stringify(spec.metadata[key])}`);
8700
+ }
8701
+ lines.push(
8702
+ "---",
8703
+ "",
8704
+ `# ${spec.name}`,
8705
+ "",
8706
+ "## Install",
8707
+ "",
8708
+ "Linux/macOS (checks SHA256SUMS and installs ~/.local/bin/ghostpaw-email):",
8709
+ "",
8710
+ "```sh",
8711
+ "curl -fsSL https://raw.githubusercontent.com/GhostPawJS/email/main/install.sh | sh",
8712
+ "```",
8713
+ "",
8714
+ "Windows x64:",
8715
+ "",
8716
+ "```powershell",
8717
+ "irm https://raw.githubusercontent.com/GhostPawJS/email/main/install.ps1 | iex",
8718
+ "```",
8719
+ "",
8720
+ `Run tools as \`${spec.bin} ...\`; use \`~/.local/bin/${spec.bin}\` if it is not on PATH.`,
8721
+ "",
8722
+ spec.about,
8723
+ "",
8724
+ "## Calling tools",
8725
+ "",
8726
+ `MCP: connect to ${spec.server}, then call a tool by name with its JSON arguments.`,
8727
+ "",
8728
+ `CLI: \`${spec.bin} call <tool> '<JSON object>'\` or \`${spec.bin} <tool> --parameter value\`.`,
8729
+ "",
8730
+ `Inspect schemas with \`${spec.bin} describe <tool>\`. Use \`--db <path>\` to select a database.`,
8731
+ ""
8732
+ );
8733
+ for (const tool of spec.tools) {
8734
+ lines.push(
8735
+ `## ${tool.name}`,
8736
+ "",
8737
+ tool.description,
8738
+ "",
8739
+ `Use when: ${tool.whenToUse ?? ""}`,
8740
+ "",
8741
+ `Not for: ${tool.whenNotToUse ?? ""}`,
8742
+ "",
8743
+ tool.readOnly ? "Read-only." : `Writes: ${tool.sideEffects ?? "state"}.`,
8744
+ "",
8745
+ "Nested requirements apply within the parent for the selected action.",
8746
+ "",
8747
+ "| Parameter | Type | Required | Values / description |",
8748
+ "| --- | --- | --- | --- |"
8749
+ );
8750
+ const row = (name, property, required) => `| ${name} | ${property.type ?? property.oneOf?.map((branch) => branch.type).join(" / ") ?? "any"} | ${required ? "yes" : "no"} | ${(property.enum ? `${property.enum.join(", ")}. ` : "") + (property.description ?? "").replaceAll("|", "\\|").replaceAll("\n", " ")} |`;
8751
+ const fields = (schema, prefix = "") => {
8752
+ const properties = Object.entries(schema.properties ?? {});
8753
+ for (const [name, property] of properties) {
8754
+ if (prefix && properties.length > 8 && !schema.required?.includes(name)) continue;
8755
+ lines.push(row(`${prefix}${name}`, property, schema.required?.includes(name) ?? false));
8756
+ const objects = [property, ...property.oneOf ?? []].filter((s4) => s4.properties);
8757
+ if (!objects.length)
8758
+ for (const branch of tool.inputSchema.oneOf ?? []) {
8759
+ const nested = branch.properties?.[name];
8760
+ if (nested?.properties) objects.push(nested);
8761
+ }
8762
+ const merged = { properties: {}, required: [] };
8763
+ for (const object of objects) {
8764
+ Object.assign(merged.properties ?? {}, object.properties);
8765
+ merged.required = [.../* @__PURE__ */ new Set([...merged.required ?? [], ...object.required ?? []])];
8766
+ }
8767
+ if (objects.length) fields(merged, `${prefix}${name}.`);
8768
+ }
8769
+ };
8770
+ fields(tool.inputSchema);
8771
+ lines.push("", "Examples:", "", "```sh");
8772
+ const actions = tool.inputSchema.properties?.action?.enum?.slice(0, 3) ?? [void 0];
8773
+ for (const action of actions) {
8774
+ const input = schemaExample(tool.inputSchema, action === void 0 ? {} : { action });
8775
+ lines.push(`${spec.bin} call ${tool.name} '${JSON.stringify(input)}'`);
8776
+ }
8777
+ lines.push("```");
8778
+ lines.push("");
8779
+ }
8780
+ lines.push(
8781
+ "## Workflow guides",
8782
+ "",
8783
+ ...spec.workflows.map(
8784
+ (workflow) => `- \`${spec.bin} skill ${workflow.name}\` ([${workflow.name}](${referencesBase}/${workflow.name}.md)): ${workflow.description}`
8785
+ ),
8786
+ "",
8787
+ "## Principles",
8788
+ "",
8789
+ ...spec.principles.map((principle) => `- ${principle}`),
8790
+ ""
8791
+ );
8792
+ if (spec.packageName)
8793
+ lines.push(
8794
+ "## Without the binary",
8795
+ "",
8796
+ `For npm-based environments (Node 24+): \`npx -y ${spec.packageName} ...\`.`,
8797
+ "",
8798
+ `Harnesses that embed it in code can import \`${spec.packageName}\` as a library.`,
8799
+ ""
8800
+ );
8801
+ return lines.join("\n");
8802
+ }
8803
+ var init_skill_markdown = __esm({
8804
+ "src/surfaces/skill_markdown.ts"() {
8805
+ init_schema_example();
8260
8806
  }
8261
8807
  });
8262
8808
 
@@ -8275,7 +8821,7 @@ var init_email_skill_spec = __esm({
8275
8821
  name: "email",
8276
8822
  description: "Read, search, compose, organize and synchronize email with a local SQLite cache. Use when managing email or searching cached messages.",
8277
8823
  license: "MIT",
8278
- compatibility: "Node.js 24 or newer. MCP stdio or email CLI.",
8824
+ compatibility: "Release binary ghostpaw-email (no runtime needed); MCP stdio via ghostpaw-email mcp.",
8279
8825
  bin: "ghostpaw-email",
8280
8826
  packageName: "@ghostpaw/email",
8281
8827
  server: "ghostpaw-email",
@@ -8298,6 +8844,8 @@ __export(email_cli_options_exports, {
8298
8844
  var emailCliOptions;
8299
8845
  var init_email_cli_options = __esm({
8300
8846
  "src/surface/email_cli_options.ts"() {
8847
+ init_cli_guide();
8848
+ init_email_skills();
8301
8849
  init_version();
8302
8850
  init_email_surface_tools();
8303
8851
  emailCliOptions = {
@@ -8324,7 +8872,19 @@ var init_email_cli_options = __esm({
8324
8872
  const { serveEmailMcp: serveEmailMcp2 } = await Promise.resolve().then(() => (init_serve_email_mcp(), serve_email_mcp_exports));
8325
8873
  await serveEmailMcp2(options.db === void 0 ? {} : { dbPath: options.db });
8326
8874
  },
8327
- skill: async () => {
8875
+ skill: async (args = []) => {
8876
+ const guides = [...emailSkills, cliGuide];
8877
+ if (args[0] === "--help" || args[0] === "-h")
8878
+ return "Usage: ghostpaw-email skill\n ghostpaw-email skill --list\n ghostpaw-email skill <guide>\n";
8879
+ if (args[0] === "--list")
8880
+ return `${guides.map((guide) => `${guide.name} ${guide.description.replace(/\s+/g, " ")}`).join("\n")}
8881
+ `;
8882
+ if (args.length) {
8883
+ const guide = guides.find((guide2) => guide2.name === args[0]);
8884
+ if (!guide || args.length !== 1)
8885
+ throw new Error(`unknown guide ${args.join(" ")}; run ghostpaw-email skill --list`);
8886
+ return guide.content;
8887
+ }
8328
8888
  const { renderSkillMarkdown: renderSkillMarkdown2 } = await Promise.resolve().then(() => (init_skill_markdown(), skill_markdown_exports));
8329
8889
  const { emailSkillSpec: emailSkillSpec2 } = await Promise.resolve().then(() => (init_email_skill_spec(), email_skill_spec_exports));
8330
8890
  return renderSkillMarkdown2(emailSkillSpec2);
@@ -10465,8 +11025,8 @@ function parseAddress(raw2) {
10465
11025
  const match = /^(.+?)\s*<([^>]+)>$/.exec(raw2.trim());
10466
11026
  if (match) {
10467
11027
  const name = match[1]?.trim();
10468
- const address = match[2]?.trim() ?? "";
10469
- return name ? { name, address } : { address };
11028
+ const address2 = match[2]?.trim() ?? "";
11029
+ return name ? { name, address: address2 } : { address: address2 };
10470
11030
  }
10471
11031
  return { address: raw2.trim() };
10472
11032
  }
@@ -11099,4 +11659,6 @@ async function runEmailCli(args = process.argv.slice(2)) {
11099
11659
  }
11100
11660
 
11101
11661
  // src/cli.ts
11662
+ init_cli_version();
11663
+ markNpmEntry();
11102
11664
  await runEmailCli();