@ghostpaw/email 0.5.4 → 0.5.6

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
@@ -3,6 +3,7 @@ import g, { stdin, stdout } from 'node:process';
3
3
  import f from 'node:readline';
4
4
  import * as tty from 'node:tty';
5
5
  import { WriteStream } from 'node:tty';
6
+ import { isSea } from 'node:sea';
6
7
  import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
7
8
  import { homedir } from 'node:os';
8
9
  import { sep, dirname, join, basename, extname } from 'node:path';
@@ -779,12 +780,35 @@ ${e.cyan(d)}
779
780
  kCancel = /* @__PURE__ */ Symbol.for("cancel");
780
781
  }
781
782
  });
783
+ function markNpmEntry() {
784
+ npmEntry = true;
785
+ }
786
+ function cliVersion(version, options = {}) {
787
+ let binary = false;
788
+ try {
789
+ binary = (options.isSea ?? isSea)();
790
+ } catch {
791
+ }
792
+ const platform2 = options.platform ?? process.platform;
793
+ const target = `${platform2 === "win32" ? "windows" : platform2}-${options.arch ?? process.arch}`;
794
+ const variant = binary ? "binary" : options.npm ?? npmEntry ? "npm" : "library";
795
+ if (options.args?.includes("--json"))
796
+ return JSON.stringify({ name: "email", version, variant, target });
797
+ if (options.args?.includes("--short")) return version;
798
+ return `email ${version} (${binary ? `binary, ${target}` : options.npm ?? npmEntry ? "npm" : "library"})`;
799
+ }
800
+ var npmEntry;
801
+ var init_cli_version = __esm({
802
+ "src/cli_version.ts"() {
803
+ npmEntry = false;
804
+ }
805
+ });
782
806
 
783
807
  // src/version.ts
784
808
  var emailVersion;
785
809
  var init_version = __esm({
786
810
  "src/version.ts"() {
787
- emailVersion = "0.5.4";
811
+ emailVersion = "0.5.6";
788
812
  }
789
813
  });
790
814
  function getConfigDir() {
@@ -1212,10 +1236,212 @@ var init_errors2 = __esm({
1212
1236
  }
1213
1237
  });
1214
1238
 
1239
+ // src/surfaces/schema_example.ts
1240
+ function schemaExample(schema, seed = {}) {
1241
+ if (schema.oneOf) {
1242
+ const branch = schema.oneOf.find(
1243
+ (candidate) => Object.entries(seed).every(([key, value]) => {
1244
+ const values = candidate.properties?.[key]?.enum;
1245
+ return !values || values.includes(value);
1246
+ })
1247
+ );
1248
+ return schemaExample({ ...schema, ...branch, oneOf: void 0 }, seed);
1249
+ }
1250
+ if (schema.enum) return schema.enum[0];
1251
+ if (schema.type === "object") {
1252
+ const result = { ...seed };
1253
+ for (const key of schema.required ?? [])
1254
+ if (!(key in result)) {
1255
+ const property = schema.properties?.[key] ?? {};
1256
+ const placeholders = {
1257
+ folder: "INBOX",
1258
+ destination: "Archive",
1259
+ query: "invoice",
1260
+ subject: "Hello",
1261
+ path: "Projects",
1262
+ oldPath: "Projects",
1263
+ newPath: "Archive/Projects"
1264
+ };
1265
+ result[key] = property.type === "string" && !property.enum && placeholders[key] ? placeholders[key] : schemaExample(property);
1266
+ }
1267
+ return result;
1268
+ }
1269
+ if (schema.type === "array") return [schemaExample(schema.items ?? {})];
1270
+ if (schema.type === "integer" || schema.type === "number") return 1;
1271
+ if (schema.type === "boolean") return false;
1272
+ return schema.description?.includes("address") ? "reader@example.com" : "example";
1273
+ }
1274
+ var init_schema_example = __esm({
1275
+ "src/surfaces/schema_example.ts"() {
1276
+ }
1277
+ });
1278
+
1279
+ // src/surfaces/validate_input.ts
1280
+ function validateInput(schema, input, path = "$") {
1281
+ const errors = validate2(schema, input, path);
1282
+ if (path !== "$" || !errors.length) return errors;
1283
+ const seed = {};
1284
+ if (input && typeof input === "object") {
1285
+ for (const key of ["action", "view"])
1286
+ if (schema.properties?.[key]?.enum?.includes(input[key]))
1287
+ seed[key] = input[key];
1288
+ }
1289
+ return errors.map((error) => `${error}; pass ${JSON.stringify(schemaExample(schema, seed))}`);
1290
+ }
1291
+ function validate2(schema, input, path) {
1292
+ const errors = [];
1293
+ const matchesType = (type) => {
1294
+ switch (type) {
1295
+ case "object":
1296
+ return typeof input === "object" && input !== null && !Array.isArray(input);
1297
+ case "array":
1298
+ return Array.isArray(input);
1299
+ case "integer":
1300
+ return typeof input === "number" && Number.isInteger(input);
1301
+ case "number":
1302
+ return typeof input === "number" && Number.isFinite(input);
1303
+ case "null":
1304
+ return input === null;
1305
+ default:
1306
+ return typeof input === type;
1307
+ }
1308
+ };
1309
+ if (schema.type && !(Array.isArray(schema.type) ? schema.type : [schema.type]).some(matchesType)) {
1310
+ return [`${path}: expected ${String(schema.type)}`];
1311
+ }
1312
+ if (schema.enum && !schema.enum.some((value) => JSON.stringify(value) === JSON.stringify(input)))
1313
+ errors.push(`${path}: expected one of ${JSON.stringify(schema.enum)}`);
1314
+ if (schema.oneOf) {
1315
+ const branches = schema.oneOf.map((branch) => validate2(branch, input, path));
1316
+ if (!branches.some((errors2) => errors2.length === 0)) {
1317
+ const record = input && typeof input === "object" ? input : {};
1318
+ const selected = schema.oneOf.findIndex(
1319
+ (branch) => ["action", "view"].some((key) => branch.properties?.[key]?.enum?.includes(record[key]))
1320
+ );
1321
+ errors.push(...branches[selected >= 0 ? selected : 0] ?? []);
1322
+ }
1323
+ }
1324
+ if (typeof input === "object" && input !== null && !Array.isArray(input)) {
1325
+ const record = input;
1326
+ for (const name of schema.required ?? [])
1327
+ if (!Object.hasOwn(record, name)) errors.push(`${path}.${name}: required`);
1328
+ for (const [name, property] of Object.entries(schema.properties ?? {}))
1329
+ if (Object.hasOwn(record, name))
1330
+ errors.push(...validate2(property, record[name], `${path}.${name}`));
1331
+ }
1332
+ if (Array.isArray(input) && schema.items)
1333
+ input.forEach((value, index) => {
1334
+ errors.push(...validate2(schema.items, value, `${path}[${index}]`));
1335
+ });
1336
+ return errors;
1337
+ }
1338
+ var init_validate_input = __esm({
1339
+ "src/surfaces/validate_input.ts"() {
1340
+ init_schema_example();
1341
+ }
1342
+ });
1343
+
1344
+ // src/tools/input_schema.ts
1345
+ function emailInputSchema(name, schema) {
1346
+ const discriminator = name === "mail_read" ? "view" : "action";
1347
+ const actions = schema.properties?.[discriminator]?.enum;
1348
+ if (!actions || name === "mail_sync") return schema;
1349
+ return {
1350
+ ...schema,
1351
+ oneOf: actions.map((value) => {
1352
+ const action = String(value);
1353
+ let required = [];
1354
+ let input;
1355
+ if (name === "mail_read") {
1356
+ if (action === "thread") required = ["threadId"];
1357
+ if (["message", "attachment", "eml"].includes(action)) required = ["folder", "uid"];
1358
+ } else if (name === "mail_compose") {
1359
+ if (action !== "send_draft") {
1360
+ required.push("input");
1361
+ input = {
1362
+ ...payload,
1363
+ required: ["send", "save_draft", "update_draft"].includes(action) ? ["to", "subject"] : action === "forward" ? ["to"] : []
1364
+ };
1365
+ }
1366
+ if (["reply", "forward"].includes(action)) required.push("folder", "uid");
1367
+ if (["update_draft", "send_draft"].includes(action)) required.push("uid");
1368
+ } else if (name === "mail_organize") {
1369
+ required = action === "rename_folder" ? ["oldPath", "newPath"] : action.endsWith("_folder") ? ["path"] : ["folder", "uids"];
1370
+ if (["copy", "move"].includes(action)) required.push("destination");
1371
+ if (action.endsWith("_labels")) required.push("labels");
1372
+ }
1373
+ return {
1374
+ type: "object",
1375
+ required: [...schema.required ?? [], ...required],
1376
+ properties: {
1377
+ ...schema.properties,
1378
+ [discriminator]: { ...schema.properties?.[discriminator], enum: [value] },
1379
+ ...input ? { input } : {}
1380
+ }
1381
+ };
1382
+ })
1383
+ };
1384
+ }
1385
+ var address, recipients, payload;
1386
+ var init_input_schema = __esm({
1387
+ "src/tools/input_schema.ts"() {
1388
+ address = {
1389
+ type: "object",
1390
+ required: ["address"],
1391
+ properties: {
1392
+ address: { type: "string", description: "Email address." },
1393
+ name: { type: "string", description: "Display name." }
1394
+ }
1395
+ };
1396
+ recipients = {
1397
+ type: "array",
1398
+ items: address,
1399
+ description: "Recipient addresses."
1400
+ };
1401
+ payload = {
1402
+ type: "object",
1403
+ properties: {
1404
+ from: address,
1405
+ sender: address,
1406
+ envelopeFrom: address,
1407
+ replyTo: address,
1408
+ to: recipients,
1409
+ cc: recipients,
1410
+ bcc: recipients,
1411
+ subject: { type: "string", description: "Message subject." },
1412
+ text: { type: "string", description: "Plain text body." },
1413
+ html: { type: "string", description: "HTML body." },
1414
+ replyAll: { type: "boolean", description: "Reply to all original recipients." },
1415
+ mode: { type: "string", enum: ["inline", "attachment"] },
1416
+ attachments: {
1417
+ type: "array",
1418
+ description: "Message attachments.",
1419
+ items: {
1420
+ type: "object",
1421
+ required: ["filename", "content"],
1422
+ properties: {
1423
+ filename: { type: "string" },
1424
+ content: { description: "Attachment bytes (Buffer in library calls)." },
1425
+ mimeType: { type: "string" },
1426
+ inline: { type: "boolean" },
1427
+ contentId: { type: "string" }
1428
+ }
1429
+ }
1430
+ },
1431
+ inReplyTo: { type: "string" },
1432
+ references: { type: "array", items: { type: "string" } },
1433
+ headers: { type: "object" }
1434
+ }
1435
+ };
1436
+ }
1437
+ });
1438
+
1215
1439
  // src/tools/email_tools.ts
1216
1440
  var emailTools;
1217
1441
  var init_email_tools = __esm({
1218
1442
  "src/tools/email_tools.ts"() {
1443
+ init_validate_input();
1444
+ init_input_schema();
1219
1445
  emailTools = [
1220
1446
  {
1221
1447
  name: "mail_read",
@@ -1935,6 +2161,21 @@ var init_email_tools = __esm({
1935
2161
  }
1936
2162
  }
1937
2163
  ];
2164
+ for (const tool of emailTools) {
2165
+ Object.assign(tool.inputSchema, emailInputSchema(tool.name, tool.inputSchema));
2166
+ const handler = tool.handler;
2167
+ tool.handler = async (ctx, input) => {
2168
+ const errors = validateInput(tool.inputSchema, input);
2169
+ if (errors.length)
2170
+ return {
2171
+ outcome: "error",
2172
+ summary: errors.join("; "),
2173
+ entities: [],
2174
+ nextSteps: errors
2175
+ };
2176
+ return handler(ctx, input);
2177
+ };
2178
+ }
1938
2179
  }
1939
2180
  });
1940
2181
 
@@ -2233,8 +2474,8 @@ async function authenticate(dispatcher, capabilities, config) {
2233
2474
  }
2234
2475
  if ("mechanism" in config) {
2235
2476
  const { mechanism, credentials } = config;
2236
- const payload = encodeBase64(Buffer.from(JSON.stringify(credentials), "utf8"));
2237
- const res = await dispatcher.execute("AUTHENTICATE", [mechanism, payload]);
2477
+ const payload2 = encodeBase64(Buffer.from(JSON.stringify(credentials), "utf8"));
2478
+ const res = await dispatcher.execute("AUTHENTICATE", [mechanism, payload2]);
2238
2479
  if (res.tagged.status !== "OK") {
2239
2480
  throw new EmailAuthError(`${mechanism} authentication failed`, mechanism);
2240
2481
  }
@@ -3192,23 +3433,23 @@ var init_decode_bodystructure = __esm({
3192
3433
  });
3193
3434
 
3194
3435
  // src/mime/decode_encoded_words.ts
3195
- function decodeQPayload(payload) {
3436
+ function decodeQPayload(payload2) {
3196
3437
  const bytes = [];
3197
- for (let i2 = 0; i2 < payload.length; i2++) {
3198
- const c3 = payload[i2];
3438
+ for (let i2 = 0; i2 < payload2.length; i2++) {
3439
+ const c3 = payload2[i2];
3199
3440
  if (c3 === "_") {
3200
3441
  bytes.push(32);
3201
3442
  continue;
3202
3443
  }
3203
- if (c3 === "=" && i2 + 2 < payload.length) {
3204
- const h2 = payload.slice(i2 + 1, i2 + 3);
3444
+ if (c3 === "=" && i2 + 2 < payload2.length) {
3445
+ const h2 = payload2.slice(i2 + 1, i2 + 3);
3205
3446
  if (/^[0-9A-Fa-f]{2}$/.test(h2)) {
3206
3447
  bytes.push(Number.parseInt(h2, 16));
3207
3448
  i2 += 2;
3208
3449
  continue;
3209
3450
  }
3210
3451
  }
3211
- bytes.push(payload.charCodeAt(i2) & 255);
3452
+ bytes.push(payload2.charCodeAt(i2) & 255);
3212
3453
  }
3213
3454
  return Buffer.from(bytes);
3214
3455
  }
@@ -3279,9 +3520,9 @@ function parseAddressList(items) {
3279
3520
  const mailbox = s3(addrArr[2]);
3280
3521
  const host = s3(addrArr[3]);
3281
3522
  if (!mailbox || !host) continue;
3282
- const address = `${mailbox}@${host}`;
3523
+ const address2 = `${mailbox}@${host}`;
3283
3524
  const name = nameRaw ? decodeEncodedWords(nameRaw) : void 0;
3284
- out.push(name ? { name, address } : { address });
3525
+ out.push(name ? { name, address: address2 } : { address: address2 });
3285
3526
  }
3286
3527
  return out;
3287
3528
  }
@@ -5284,11 +5525,11 @@ function populateFts(db, messageId, textPlain, textHtml) {
5284
5525
  if (!row) return;
5285
5526
  const subject = row.subject != null ? String(row.subject) : "";
5286
5527
  const sender = row.from != null ? String(row.from) : "";
5287
- const recipients = row.to != null ? String(row.to) : "";
5528
+ const recipients2 = row.to != null ? String(row.to) : "";
5288
5529
  db.exec(`DELETE FROM messages_fts WHERE rowid = ${messageId}`);
5289
5530
  db.prepare(
5290
5531
  "INSERT INTO messages_fts(rowid, subject, body_text, sender, recipients) VALUES (?, ?, ?, ?, ?)"
5291
- ).run(messageId, subject, bodyText, sender, recipients);
5532
+ ).run(messageId, subject, bodyText, sender, recipients2);
5292
5533
  }
5293
5534
  var init_fts_populate = __esm({
5294
5535
  "src/sync/fts_populate.ts"() {
@@ -6982,51 +7223,6 @@ var init_cli_args = __esm({
6982
7223
  }
6983
7224
  });
6984
7225
 
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
7226
  // src/surfaces/cli_commands.ts
7031
7227
  function cliCommands(tools) {
7032
7228
  return tools.flatMap((tool) => {
@@ -7089,14 +7285,14 @@ async function runCliCommand(argv2, options) {
7089
7285
  else if (flag === "--compact") compact = true;
7090
7286
  else if (flag === "--help" || flag === "-h") help = true;
7091
7287
  else if (["--version", "-V", "-v"].includes(flag ?? "")) {
7092
- if (!quiet) stdout2.write(`${options.version}
7288
+ if (!quiet) stdout2.write(`${cliVersion(options.version, { args: argv2 })}
7093
7289
  `);
7094
7290
  return 0;
7095
7291
  } else if (flag !== "--no-color") continue;
7096
7292
  args.splice(i2--, 1);
7097
7293
  }
7098
7294
  if (args[0] === "version") {
7099
- if (!quiet) stdout2.write(`${options.version}
7295
+ if (!quiet) stdout2.write(`${cliVersion(options.version, { args: argv2 })}
7100
7296
  `);
7101
7297
  return 0;
7102
7298
  }
@@ -7148,6 +7344,7 @@ ${options.description}
7148
7344
  Commands:
7149
7345
  ${matches.map((command) => ` ${command.path}`).join("\n")}
7150
7346
  mcp, skill, tools [--json], describe <tool>, call <tool> [JSON|-], completions <bash|zsh|fish>, version
7347
+ Version output: --version --short or --version --json
7151
7348
  Global flags: --db <path>, --json, --quiet, --compact, --help/-h, --version/-V/-v, --no-color
7152
7349
  `
7153
7350
  );
@@ -7239,6 +7436,7 @@ ${JSON.stringify(record.data ?? {}, null, 2)}
7239
7436
  }
7240
7437
  var init_cli_commands = __esm({
7241
7438
  "src/surfaces/cli_commands.ts"() {
7439
+ init_cli_version();
7242
7440
  init_cli_args();
7243
7441
  init_validate_input();
7244
7442
  }
@@ -7302,7 +7500,7 @@ ${options.tools.map((tool2) => `${tool2.name} ${tool2.description}`).join("\n")
7302
7500
  return 0;
7303
7501
  }
7304
7502
  if (["--version", "-v"].includes(command)) {
7305
- stdout2.write(`${options.version}
7503
+ stdout2.write(`${cliVersion(options.version)}
7306
7504
  `);
7307
7505
  return 0;
7308
7506
  }
@@ -7320,7 +7518,11 @@ ${options.tools.map((tool2) => `${tool2.name} ${tool2.description}`).join("\n")
7320
7518
  }
7321
7519
  if (command === "skill") {
7322
7520
  if (!options.commands?.skill) return fail("skill command unavailable");
7323
- stdout2.write(await options.commands.skill());
7521
+ try {
7522
+ stdout2.write(await options.commands.skill(args));
7523
+ } catch (error) {
7524
+ return fail(error instanceof Error ? error.message : String(error), 1);
7525
+ }
7324
7526
  return 0;
7325
7527
  }
7326
7528
  if (command === "mcp") {
@@ -7432,472 +7634,315 @@ ${JSON.stringify(tool.inputSchema, null, 2)}
7432
7634
  }
7433
7635
  var init_cli = __esm({
7434
7636
  "src/surfaces/cli.ts"() {
7637
+ init_cli_version();
7435
7638
  init_cli_commands();
7436
7639
  init_surface_types();
7437
7640
  init_validate_input();
7438
7641
  }
7439
7642
  });
7440
7643
 
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
- );
7644
+ // src/skills/skill_types.ts
7645
+ function defineEmailSkill(skill) {
7646
+ return skill;
7647
+ }
7648
+ var init_skill_types = __esm({
7649
+ "src/skills/skill_types.ts"() {
7525
7650
  }
7526
7651
  });
7527
7652
 
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
- });
7653
+ // src/skills/cli-guide.ts
7654
+ var cliGuide;
7655
+ var init_cli_guide = __esm({
7656
+ "src/skills/cli-guide.ts"() {
7657
+ init_skill_types();
7658
+ cliGuide = defineEmailSkill({
7659
+ name: "cli",
7660
+ description: "Complete existing email CLI guide.",
7661
+ content: `# SKILL.md \u2014 \`email\` CLI as an Agent Tool Surface
7662
+
7663
+ The \`email\` binary is a local-first email CLI built on top of \`@ghostpaw/email\`. It exposes five
7664
+ intent-shaped commands that map directly to the library's tool layer. Agents invoke it as a
7665
+ subprocess via bash; no MCP server or standing process is needed.
7666
+
7667
+ ---
7668
+
7669
+ ## Prerequisites
7670
+
7671
+ - Node.js \u2265 24
7672
+ - Install once:
7673
+ \`\`\`bash
7674
+ npm install -g @ghostpaw/email # global install, \`email\` in PATH
7675
+ npx @ghostpaw/email account add ... # or zero-install via npx
7676
+ \`\`\`
7677
+
7678
+ ---
7679
+
7680
+ ## Account Setup
7681
+
7682
+ \`\`\`bash
7683
+ email account add \\
7684
+ --name work \\
7685
+ --imap-host imap.fastmail.com --imap-port 993 \\
7686
+ --smtp-host smtp.fastmail.com --smtp-port 587 \\
7687
+ --user me@fastmail.com --pass "app-password"
7688
+
7689
+ email account list # see all accounts
7690
+ email account set-default --name work
7691
+ email account show # shows config (password redacted)
7692
+ \`\`\`
7693
+
7694
+ ### Environment variables (no config file needed \u2014 useful in CI)
7695
+
7696
+ | Variable | Purpose |
7697
+ |---|---|
7698
+ | \`EMAIL_ACCOUNT\` | Select account by slug |
7699
+ | \`EMAIL_IMAP_HOST\` | IMAP hostname |
7700
+ | \`EMAIL_IMAP_PORT\` | IMAP port (default: 993) |
7701
+ | \`EMAIL_IMAP_TLS\` | \`"false"\` to disable TLS |
7702
+ | \`EMAIL_SMTP_HOST\` | SMTP hostname |
7703
+ | \`EMAIL_SMTP_PORT\` | SMTP port (default: 587) |
7704
+ | \`EMAIL_SMTP_TLS\` | \`"false"\` to disable TLS |
7705
+ | \`EMAIL_USER\` | Auth username |
7706
+ | \`EMAIL_PASS\` | Password auth |
7707
+ | \`EMAIL_ACCESS_TOKEN\` | OAuth2 access token |
7708
+ | \`EMAIL_REFRESH_TOKEN\` | OAuth2 refresh token |
7709
+ | \`EMAIL_CONFIG_DIR\` | Override config directory (full path) |
7710
+ | \`EMAIL_DATA_DIR\` | Override SQLite data directory (full path) |
7711
+ | \`NO_COLOR\` | Disable ANSI color output |
7712
+
7713
+ ---
7714
+
7715
+ ## \`--json\` \u2014 Machine-Readable Output
7716
+
7717
+ **Always use \`--json\` when invoking from an agent.** Every command outputs a JSON object:
7718
+
7719
+ \`\`\`json
7720
+ {
7721
+ "outcome": "success",
7722
+ "summary": "42 message(s) in INBOX.",
7723
+ "entities": [
7724
+ { "kind": "message", "id": "1921", "title": "Re: Q2 roadmap" }
7725
+ ],
7726
+ "nextSteps": [
7727
+ "Use view: \\"message\\" with folder and uid to read a specific message."
7728
+ ]
7729
+ }
7730
+ \`\`\`
7731
+
7732
+ \`outcome\` values:
7733
+ - \`"success"\` \u2014 operation completed
7734
+ - \`"no_op"\` \u2014 nothing to do (not an error)
7735
+ - \`"needs_clarification"\` \u2014 more information required; check \`nextSteps\`
7736
+ - \`"error"\` \u2014 operation failed; check \`summary\` for details and \`nextSteps\` for guidance
7737
+
7738
+ **On error, \`--json\` output still goes to stdout** (not stderr) so downstream parsers can always
7739
+ parse stdout unconditionally.
7740
+
7741
+ ---
7742
+
7743
+ ## Exit Codes
7744
+
7745
+ | Code | When |
7746
+ |---|---|
7747
+ | \`0\` | \`success\` or \`no_op\` |
7748
+ | \`1\` | Missing required flag, invalid value, body required |
7749
+ | \`2\` | No config, malformed config, unknown account, no default account |
7750
+ | \`3\` | Authentication failure |
7751
+ | \`4\` | Network / connection failure |
7752
+ | \`5\` | Tool returned \`outcome: "error"\` |
7753
+ | \`6\` | Tool returned \`outcome: "needs_clarification"\` |
7754
+ | \`127\` | Unexpected / unhandled error |
7755
+
7756
+ ---
7757
+
7758
+ ## Commands
7759
+
7760
+ ### \`email read [view]\`
7761
+
7762
+ Read mailbox state. Default view: \`queue\` (INBOX).
7763
+
7764
+ \`\`\`bash
7765
+ email read --json # queue view, INBOX
7766
+ email read folders --json # list all folders
7767
+ email read queue --folder Sent --limit 20 --json
7768
+ email read queue --unread-only --json
7769
+ email read thread --thread-id <id> --json
7770
+ email read message --folder INBOX --uid 1921 --json
7771
+ email read attachment --folder INBOX --uid 1921 --json # list attachments
7772
+ email read eml --folder INBOX --uid 1921 # raw EML bytes to stdout
7773
+ \`\`\`
7774
+
7775
+ **\`eml\` view:** writes raw EML bytes to stdout. In \`--json\` mode the bytes are base64-encoded
7776
+ under a \`"data"\` key.
7777
+
7778
+ \`\`\`bash
7779
+ email read eml --folder INBOX --uid 42 > message.eml
7780
+ email read eml --folder INBOX --uid 42 --json | jq -r '.data' | base64 -d > message.eml
7781
+ \`\`\`
7782
+
7783
+ ### \`email search <query>\`
7784
+
7785
+ Search messages via local FTS5 (default) or remote IMAP SEARCH.
7786
+
7787
+ \`\`\`bash
7788
+ email search "invoice" --json
7789
+ email search "from:boss@work.com subject:quarterly" --json
7790
+ email search "budget 2026" --folder Archive --limit 10 --json
7791
+ email search "urgent" --mode remote --json
7792
+ email search "report" --since 2026-01-01 --before 2026-04-01 --json
7793
+ email search "contract" --has-attachments --json
7794
+ \`\`\`
7795
+
7796
+ ### \`email compose <action>\`
7797
+
7798
+ Compose and send email. Body comes from \`--body\` or piped stdin.
7799
+
7800
+ \`\`\`bash
7801
+ # Send
7802
+ email compose send --to alice@example.com --subject "Hello" --body "Hi there" --json
7803
+ echo "Meeting at 3pm?" | email compose send --to alice@example.com --subject "Quick question"
7565
7804
 
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
- });
7805
+ # Reply (body from stdin)
7806
+ echo "Sounds good!" | email compose reply --folder INBOX --uid 1921
7578
7807
 
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 ? `
7808
+ # Reply-all
7809
+ email compose reply --folder INBOX --uid 1921 --body "Thanks all" --reply-all --json
7651
7810
 
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
- });
7811
+ # Forward
7812
+ email compose forward --folder INBOX --uid 1921 --to bob@example.com --body "FYI" --json
7721
7813
 
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
- });
7814
+ # Attach files (comma-separated paths)
7815
+ email compose send --to a@b.com --subject "Report" --body "See attached" \\
7816
+ --attach /path/to/report.pdf,/path/to/data.csv --json
7753
7817
 
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
- });
7818
+ # Drafts
7819
+ email compose draft --save --to a@b.com --subject "Draft" --body "WIP" --json
7820
+ email compose draft --send-draft 42 --json
7821
+ \`\`\`
7761
7822
 
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"() {
7823
+ ### \`email organize <action>\`
7824
+
7825
+ Organize messages and folders. \`--uids\` accepts comma-separated UIDs.
7826
+
7827
+ \`\`\`bash
7828
+ email organize mark-read --folder INBOX --uids 1,2,3 --json
7829
+ email organize star --folder INBOX --uids 42 --json
7830
+ email organize archive --folder INBOX --uids 1921,1922 --json
7831
+ email organize trash --folder INBOX --uids 1800 --json
7832
+ email organize move --folder INBOX --uids 100 --destination Archive --json
7833
+ email organize set-labels --folder INBOX --uids 42 --labels "work,priority" --json
7834
+ email organize create-folder --path "Projects/2026" --json
7835
+ email organize rename-folder --old-path "Projects" --new-path "Work/Projects" --json
7836
+ email organize delete-folder --path "OldFolder" --json
7837
+ \`\`\`
7838
+
7839
+ ### \`email sync [action]\`
7840
+
7841
+ Manage IMAP connection and sync local SQLite state. Default action: \`sync\`.
7842
+
7843
+ \`\`\`bash
7844
+ email sync --json # sync all folders (default)
7845
+ email sync sync --folders INBOX,Sent --json
7846
+ email sync sync --bodies all --json # fetch all bodies
7847
+ email sync refresh-folders --json
7848
+ email sync connect --json
7849
+ email sync disconnect --json
7850
+ email sync watch --json # syncs then exits; continuous watching needs the library
7851
+ \`\`\`
7852
+
7853
+ ---
7854
+
7855
+ ## Multi-Step Workflow Examples
7856
+
7857
+ ### Triage inbox
7858
+
7859
+ \`\`\`bash
7860
+ # Get unread messages
7861
+ UNREAD=$(email read queue --unread-only --json)
7862
+ echo "$UNREAD" | jq '.entities[].id'
7863
+
7864
+ # Archive a batch
7865
+ email organize archive --folder INBOX --uids 1,2,3 --json
7866
+ \`\`\`
7867
+
7868
+ ### Read and reply
7869
+
7870
+ \`\`\`bash
7871
+ # Read a specific message
7872
+ MSG=$(email read message --folder INBOX --uid 1921 --json)
7873
+ echo "$MSG" | jq '.summary'
7874
+
7875
+ # Reply
7876
+ echo "Thanks, will do." | email compose reply --folder INBOX --uid 1921 --json
7877
+ \`\`\`
7878
+
7879
+ ### Search and act
7880
+
7881
+ \`\`\`bash
7882
+ # Find all invoices from last month
7883
+ RESULTS=$(email search "invoice" --since 2026-02-01 --before 2026-03-01 --json)
7884
+ UIDS=$(echo "$RESULTS" | jq -r '.entities[].id' | tr '\\n' ',' | sed 's/,$//')
7885
+
7886
+ # Move them to an Archive folder
7887
+ email organize move --folder INBOX --uids "$UIDS" --destination Archive --json
7888
+ \`\`\`
7889
+
7890
+ ### Full sync then read
7891
+
7892
+ \`\`\`bash
7893
+ email sync --json
7894
+ email read queue --limit 20 --json
7895
+ \`\`\`
7896
+
7897
+ ### Export an attachment
7898
+
7899
+ \`\`\`bash
7900
+ # List attachments
7901
+ ATTS=$(email read attachment --folder INBOX --uid 1921 --json)
7902
+ PART=$(echo "$ATTS" | jq -r '.entities[0].id')
7903
+
7904
+ # Download raw bytes
7905
+ email read attachment --folder INBOX --uid 1921 --part-path "$PART" > attachment.pdf
7906
+ \`\`\`
7907
+
7908
+ ---
7909
+
7910
+ ## Error Handling for Agents
7911
+
7912
+ - **Always check \`outcome\`** before acting on \`entities\`. Even exit code 0 can return \`"no_op"\`.
7913
+ - **Do not retry auth errors** (exit 3) \u2014 they require credential changes.
7914
+ - **On \`needs_clarification\`** (exit 6) \u2014 read \`nextSteps\` and ask the user for more information.
7915
+ - **On \`error\`** (exit 5) \u2014 the tool's \`summary\` and \`nextSteps\` contain actionable guidance.
7916
+ - **Network errors** (exit 4) \u2014 retry after a brief pause; check host/port if it persists.
7917
+
7918
+ ---
7919
+
7920
+ ## Piping Patterns
7921
+
7922
+ \`\`\`bash
7923
+ # Pipe body from stdin
7924
+ echo "Hello" | email compose send --to x@y.com --subject "Hi"
7925
+
7926
+ # Export EML and forward to another tool
7927
+ email read eml --folder INBOX --uid 42 | mail -s "fwd" target@example.com
7928
+
7929
+ # JSON pipeline
7930
+ email read queue --json | jq '.entities[] | select(.title | test("invoice"; "i")) | .id'
7931
+
7932
+ # Quiet mode \u2014 only exit code matters
7933
+ email organize archive --folder INBOX --uids 42 --quiet && echo "archived"
7934
+ \`\`\`
7935
+
7936
+ ---
7937
+
7938
+ ## What the CLI Does NOT Do
7939
+
7940
+ - **No persistent daemon.** Every invocation opens a fresh IMAP connection and closes it cleanly.
7941
+ - **No continuous IDLE watch.** \`email sync watch\` syncs once and exits. For push-style updates,
7942
+ use \`Mailbox.network.watch()\` from the library directly.
7943
+ - **No interactive prompts.** All input comes from flags or stdin.
7944
+ `
7945
+ });
7901
7946
  }
7902
7947
  });
7903
7948
 
@@ -8148,115 +8193,621 @@ Failure handling:
8148
8193
  }
8149
8194
  });
8150
8195
 
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
- });
8196
+ // src/skills/search-and-act.ts
8197
+ var searchAndActSkill;
8198
+ var init_search_and_act = __esm({
8199
+ "src/skills/search-and-act.ts"() {
8200
+ init_skill_types();
8201
+ searchAndActSkill = defineEmailSkill({
8202
+ name: "search-and-act",
8203
+ description: "Find messages matching criteria (local FTS first, remote IMAP SEARCH as fallback), verify targets, then act \u2014 organize, reply, or present.",
8204
+ content: `# Search and Act
8205
+
8206
+ Primary tools:
8207
+ - \`mail_search\`
8208
+ - \`mail_read\`
8209
+ - \`mail_organize\`
8210
+ - \`mail_compose\`
8211
+
8212
+ Steps:
8213
+ 1. Start with \`mail_search { query, mode: "local" }\` \u2014 FTS is fast, works offline, and searches subjects, body text, and sender fields simultaneously.
8214
+ - Add \`folder\` to restrict to a specific mailbox.
8215
+ - Add \`since\` / \`before\` (ISO date strings) to narrow by date range.
8216
+ - Add \`hasAttachments: true\` or \`unreadOnly: true\` for quick filters.
8217
+ 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.
8218
+ - Remote search requires an active IMAP session \u2014 run \`mail_sync { action: "connect" }\` first if not connected.
8219
+ - Remote search returns UIDs only \u2014 always follow up with \`mail_read { view: "message" }\` to get content.
8220
+ 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.
8221
+ 4. Decide action based on what you found:
8222
+ - Organize \u2192 \`mail_organize\` with the appropriate action (archive, move, star, mark_read, etc.).
8223
+ - Reply \u2192 hand off to the \`read-and-reply\` skill.
8224
+ - Forward \u2192 \`mail_compose { action: "forward", folder, uid, input }\`.
8225
+ - Present only \u2192 return the entity list with subjects and UIDs.
8226
+
8227
+ Outcome handling:
8228
+ - Empty local results do not mean the mail doesn't exist \u2014 always try remote search before concluding there are no matches.
8229
+ - Remote search returns UIDs, not message content; reading before acting is not optional.
8230
+ - 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.
8231
+ - FTS queries support stemming and phrase matching; if an exact term fails, try a root word or shorter phrase.
8232
+
8233
+ Failure handling:
8234
+ - Do not act on search results without reading the target first \u2014 subject-only matches can mislead.
8235
+ - Do not run remote search in a loop \u2014 one local attempt and one remote attempt is sufficient before widening or abandoning the query.
8236
+ - If \`mode: "remote"\` fails because there is no active session, surface the connection error and suggest \`connect-and-sync\` first.`
8237
+ });
8238
+ }
8239
+ });
8240
+
8241
+ // src/skills/triage-inbox.ts
8242
+ var triageInboxSkill;
8243
+ var init_triage_inbox = __esm({
8244
+ "src/skills/triage-inbox.ts"() {
8245
+ init_skill_types();
8246
+ triageInboxSkill = defineEmailSkill({
8247
+ name: "triage-inbox",
8248
+ 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.",
8249
+ content: `# Triage Inbox
8250
+
8251
+ Primary tools:
8252
+ - \`mail_sync\`
8253
+ - \`mail_read\`
8254
+ - \`mail_search\`
8255
+ - \`mail_organize\`
8256
+
8257
+ Steps:
8258
+ 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.
8259
+ 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.
8260
+ 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 }\`.
8261
+ 4. For messages that are part of an ongoing thread, use \`mail_read { view: "thread", threadId }\` to see the full conversation before deciding.
8262
+ 5. Categorise each message:
8263
+ - Needs a reply \u2192 hand off to the \`read-and-reply\` skill.
8264
+ - Contains an attachment \u2192 hand off to the \`attachment-workflow\` skill.
8265
+ - Informational / done \u2192 \`mail_organize { action: "archive", folder, uids }\`.
8266
+ - Spam / junk \u2192 \`mail_organize { action: "junk", folder, uids }\`.
8267
+ - Important but deferred \u2192 \`mail_organize { action: "star", folder, uids }\`.
8268
+ 6. Apply bulk flag operations before disposition: \`mark_read\` first, then \`archive\`/\`trash\`/\`move\` in separate calls.
8269
+
8270
+ Outcome handling:
8271
+ - If sync returns \`totalNew: 0\`, the inbox is already current \u2014 proceed directly to the queue read.
8272
+ - 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.
8273
+ - If a thread has many messages, read only the most recent before deciding; fetch earlier messages only when context is explicitly needed.
8274
+
8275
+ Failure handling:
8276
+ - Do not archive without reading when the message is from a known sender with an active thread.
8277
+ - Do not bulk-trash without confirming the source folder is correct \u2014 junk detection and legit mail can look similar.
8278
+ - Do not triage in one pass if the inbox has more than 50 messages \u2014 paginate with \`limit\` and \`offset\` to avoid missing messages.`
8279
+ });
8280
+ }
8281
+ });
8282
+
8283
+ // src/skills/email_skills.ts
8284
+ var emailSkills;
8285
+ var init_email_skills = __esm({
8286
+ "src/skills/email_skills.ts"() {
8287
+ init_attachment_workflow();
8288
+ init_compose_and_send();
8289
+ init_connect_and_sync();
8290
+ init_organize_bulk();
8291
+ init_read_and_reply();
8292
+ init_recover_from_disruption();
8293
+ init_search_and_act();
8294
+ init_triage_inbox();
8295
+ emailSkills = [
8296
+ triageInboxSkill,
8297
+ readAndReplySkill,
8298
+ connectAndSyncSkill,
8299
+ searchAndActSkill,
8300
+ composeAndSendSkill,
8301
+ organizeBulkSkill,
8302
+ attachmentWorkflowSkill,
8303
+ recoverFromDisruptionSkill
8304
+ ];
8305
+ }
8306
+ });
8307
+
8308
+ // src/surface/email_surface_tools.ts
8309
+ var emailMcpTools, emailSurfaceTools;
8310
+ var init_email_surface_tools = __esm({
8311
+ "src/surface/email_surface_tools.ts"() {
8312
+ init_read();
8313
+ init_store();
8314
+ init_aligned();
8315
+ emailMcpTools = emailTools2.map((tool) => ({
8316
+ ...tool,
8317
+ inputSchema: { ...tool.inputSchema, type: "object" },
8318
+ async handler(db, input) {
8319
+ const local = tool.name === "mail_search" && input.mode !== "remote" || tool.name === "mail_read" && !input.refresh && input.view !== "eml";
8320
+ try {
8321
+ if (local) {
8322
+ const accountId = listAccounts(db)[0]?.id ?? 1;
8323
+ return await tool.handler(
8324
+ { read: createReadSurface(db, accountId) },
8325
+ input
8326
+ );
8327
+ }
8328
+ const { resolveAccount: resolveAccount2, buildEmailConfig: buildEmailConfig2 } = await Promise.resolve().then(() => (init_account(), account_exports));
8329
+ const config = buildEmailConfig2(resolveAccount2());
8330
+ const { ImapSession: ImapSession2 } = await Promise.resolve().then(() => (init_session(), session_exports));
8331
+ const { createWriteSurface: createWriteSurface2 } = await Promise.resolve().then(() => (init_write(), write_exports));
8332
+ const { createNetworkSurface: createNetworkSurface2 } = await Promise.resolve().then(() => (init_network(), network_exports));
8333
+ const auth = config.auth;
8334
+ const username = "user" in auth ? auth.user : auth.credentials.user ?? auth.credentials.username ?? "user";
8335
+ const account = upsertAccount(db, {
8336
+ host: config.imap.host,
8337
+ port: config.imap.port,
8338
+ username
8339
+ });
8340
+ const session = new ImapSession2(config);
8341
+ try {
8342
+ const explicitConnect = tool.name === "mail_sync" && ["connect", "reconnect", "disconnect"].includes(String(input.action));
8343
+ if (!explicitConnect) await session.connect();
8344
+ return await tool.handler(
8345
+ {
8346
+ read: createReadSurface(db, account.id, { session }),
8347
+ write: createWriteSurface2(db, { config, accountId: account.id, session }),
8348
+ network: createNetworkSurface2(db, { accountId: account.id, session })
8349
+ },
8350
+ input
8351
+ );
8352
+ } finally {
8353
+ await session.disconnect();
8354
+ }
8355
+ } catch (error) {
8356
+ return {
8357
+ ok: false,
8358
+ outcome: "error",
8359
+ summary: error instanceof Error ? error.message : String(error),
8360
+ next: [
8361
+ {
8362
+ kind: "use_tool",
8363
+ 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."
8364
+ }
8365
+ ],
8366
+ data: { entities: [] }
8367
+ };
8368
+ }
8369
+ }
8370
+ }));
8371
+ emailSurfaceTools = /* @__PURE__ */ emailMcpTools.map(
8372
+ (tool) => ({
8373
+ ...tool,
8374
+ cli: {
8375
+ noun: "mail",
8376
+ verb: tool.name.slice(5),
8377
+ ...tool.name === "mail_search" ? { positionals: ["query"] } : {},
8378
+ ...tool.inputSchema.properties?.action?.enum ? {
8379
+ action: {
8380
+ property: "action",
8381
+ verbs: Object.fromEntries(
8382
+ tool.inputSchema.properties.action.enum.map((value) => [
8383
+ String(value),
8384
+ value === "save_draft" ? "draft" : String(value).replaceAll("_", "-")
8385
+ ])
8386
+ )
8387
+ }
8388
+ } : {}
8389
+ }
8390
+ })
8391
+ );
8392
+ }
8393
+ });
8394
+
8395
+ // src/surface/open_email_db.ts
8396
+ var open_email_db_exports = {};
8397
+ __export(open_email_db_exports, {
8398
+ openEmailDb: () => openEmailDb
8399
+ });
8400
+ async function openEmailDb(path) {
8401
+ const original = process.emitWarning;
8402
+ process.emitWarning = ((warning, ...args) => {
8403
+ 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;
8404
+ const message = warning instanceof Error ? warning.message : warning;
8405
+ if (type === "ExperimentalWarning" && message.startsWith("SQLite is an experimental feature"))
8406
+ return;
8407
+ Reflect.apply(original, process, [warning, ...args]);
8408
+ });
8409
+ let sqlite;
8410
+ try {
8411
+ sqlite = await import('node:sqlite');
8412
+ } finally {
8413
+ process.emitWarning = original;
8414
+ }
8415
+ if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true });
8416
+ const db = new sqlite.DatabaseSync(path);
8417
+ try {
8418
+ db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;");
8419
+ const context = db;
8420
+ initSchema(context);
8421
+ return context;
8422
+ } catch (error) {
8423
+ db.close();
8424
+ throw error;
8425
+ }
8426
+ }
8427
+ var init_open_email_db = __esm({
8428
+ "src/surface/open_email_db.ts"() {
8429
+ init_schema();
8430
+ }
8431
+ });
8432
+
8433
+ // src/surface/resolve_email_db_path.ts
8434
+ var resolve_email_db_path_exports = {};
8435
+ __export(resolve_email_db_path_exports, {
8436
+ resolveEmailDbPath: () => resolveEmailDbPath
8437
+ });
8438
+ function resolveEmailDbPath(options = {}) {
8439
+ return options.flag ?? ((options.env ?? process.env).GHOSTPAW_EMAIL_DB || join(homedir(), ".ghostpaw", "email.db"));
8440
+ }
8441
+ var init_resolve_email_db_path = __esm({
8442
+ "src/surface/resolve_email_db_path.ts"() {
8443
+ }
8444
+ });
8445
+
8446
+ // src/surfaces/mcp_server.ts
8447
+ function createMcpServer(options) {
8448
+ let initialized = false;
8449
+ let context;
8450
+ const serverInfo = { name: options.name, version: options.version };
8451
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8452
+ const error = (id, code, message, data) => ({
8453
+ jsonrpc: "2.0",
8454
+ id,
8455
+ error: { code, message, ...data === void 0 ? {} : { data } }
8456
+ });
8457
+ const handleMessage = async (msg) => {
8458
+ 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")
8459
+ return error(null, -32600, "Invalid Request");
8460
+ if (!Object.hasOwn(msg, "id")) return void 0;
8461
+ const id = msg.id;
8462
+ if (msg.params !== void 0 && !record(msg.params)) return error(id, -32602, "Invalid params");
8463
+ const params = record(msg.params) ? msg.params : {};
8464
+ const meta = record(params._meta) ? params._meta : {};
8465
+ const requested = meta["io.modelcontextprotocol/protocolVersion"];
8466
+ const modern = requested !== void 0;
8467
+ if (modern && !MCP_SUPPORTED_PROTOCOL_VERSIONS.includes(
8468
+ requested
8469
+ ))
8470
+ return error(id, -32022, "Unsupported protocol version", {
8471
+ supported: [...MCP_SUPPORTED_PROTOCOL_VERSIONS],
8472
+ requested
8473
+ });
8474
+ const result = (value) => ({
8475
+ jsonrpc: "2.0",
8476
+ id,
8477
+ result: modern ? {
8478
+ ...value,
8479
+ resultType: "complete",
8480
+ _meta: { "io.modelcontextprotocol/serverInfo": serverInfo }
8481
+ } : value
8482
+ });
8483
+ if (!modern && msg.method === "initialize") {
8484
+ initialized = true;
8485
+ const version = MCP_SUPPORTED_PROTOCOL_VERSIONS.slice(1).find((v2) => v2 === params.protocolVersion) ?? "2025-11-25";
8486
+ return result({
8487
+ protocolVersion: version,
8488
+ capabilities: { tools: { listChanged: false } },
8489
+ serverInfo: { ...serverInfo, ...options.title ? { title: options.title } : {} },
8490
+ ...options.instructions ? { instructions: options.instructions } : {}
8491
+ });
8492
+ }
8493
+ if (!modern && !initialized)
8494
+ return error(
8495
+ id,
8496
+ -32602,
8497
+ `Protocol version required. Supported versions: ${MCP_SUPPORTED_PROTOCOL_VERSIONS.join(", ")}`
8498
+ );
8499
+ if (modern && !record(meta["io.modelcontextprotocol/clientCapabilities"]))
8500
+ return error(id, -32602, "clientCapabilities must be an object");
8501
+ switch (msg.method) {
8502
+ case "ping":
8503
+ return result({});
8504
+ case "server/discover":
8505
+ return result({
8506
+ supportedVersions: [...MCP_SUPPORTED_PROTOCOL_VERSIONS],
8507
+ capabilities: { tools: {} },
8508
+ ...options.instructions ? { instructions: options.instructions } : {},
8509
+ ttlMs: 6e4,
8510
+ cacheScope: "public"
8511
+ });
8512
+ case "tools/list":
8513
+ return result({
8514
+ tools: options.tools.map((tool) => ({
8515
+ name: tool.name,
8516
+ ...tool.title ? { title: tool.title } : {},
8517
+ description: tool.description + (tool.whenToUse ? `
8518
+
8519
+ Use when: ${tool.whenToUse}` : "") + (tool.whenNotToUse ? `
8520
+ Not for: ${tool.whenNotToUse}` : ""),
8521
+ inputSchema: tool.inputSchema,
8522
+ annotations: options.annotations?.(tool) ?? {
8523
+ readOnlyHint: tool.readOnly ?? false,
8524
+ destructiveHint: !tool.readOnly,
8525
+ idempotentHint: tool.readOnly ?? false,
8526
+ openWorldHint: false
8527
+ }
8528
+ })),
8529
+ ...modern ? { ttlMs: 6e4, cacheScope: "public" } : {}
8530
+ });
8531
+ case "tools/call": {
8532
+ const tool = options.tools.find((tool2) => tool2.name === params.name);
8533
+ if (!tool) return error(id, -32602, `Unknown tool: ${String(params.name)}`);
8534
+ const input = params.arguments === void 0 ? {} : params.arguments;
8535
+ const errors = validateInput(tool.inputSchema, input);
8536
+ if (errors.length)
8537
+ return result({ content: [{ type: "text", text: errors.join("\n") }], isError: true });
8538
+ try {
8539
+ context ??= Promise.resolve().then(options.context);
8540
+ const value = await tool.handler(await context, input);
8541
+ return result({
8542
+ content: [{ type: "text", text: JSON.stringify(value) ?? "null" }],
8543
+ ...record(value) ? { structuredContent: value } : {},
8544
+ isError: (options.isErrorResult ?? isErrorResult)(value)
8545
+ });
8546
+ } catch (cause) {
8547
+ return result({
8548
+ content: [
8549
+ { type: "text", text: cause instanceof Error ? cause.message : String(cause) }
8550
+ ],
8551
+ isError: true
8552
+ });
8553
+ }
8554
+ }
8555
+ default:
8556
+ return error(id, -32601, "Method not found");
8557
+ }
8558
+ };
8559
+ return {
8560
+ handleMessage,
8561
+ async handleLine(line) {
8562
+ let msg;
8563
+ try {
8564
+ msg = JSON.parse(line);
8565
+ } catch {
8566
+ return JSON.stringify(error(null, -32700, "Parse error"));
8567
+ }
8568
+ const response = await handleMessage(msg);
8569
+ return response === void 0 ? void 0 : JSON.stringify(response);
8570
+ }
8571
+ };
8572
+ }
8573
+ var MCP_LATEST_PROTOCOL_VERSION, MCP_SUPPORTED_PROTOCOL_VERSIONS;
8574
+ var init_mcp_server = __esm({
8575
+ "src/surfaces/mcp_server.ts"() {
8576
+ init_surface_types();
8577
+ init_validate_input();
8578
+ MCP_LATEST_PROTOCOL_VERSION = "2026-07-28";
8579
+ MCP_SUPPORTED_PROTOCOL_VERSIONS = [
8580
+ MCP_LATEST_PROTOCOL_VERSION,
8581
+ "2025-11-25",
8582
+ "2025-06-18",
8583
+ "2025-03-26",
8584
+ "2024-11-05"
8585
+ ];
8586
+ }
8587
+ });
8588
+
8589
+ // src/surfaces/mcp_stdio.ts
8590
+ async function serveMcpStdio(server, options = {}) {
8591
+ const input = options.input ?? process.stdin;
8592
+ const output = options.output ?? process.stdout;
8593
+ input.setEncoding("utf8");
8594
+ let buffer = "";
8595
+ const respond = async (line) => {
8596
+ if (!line.trim()) return;
8597
+ const response = await server.handleLine(line.replace(/\r$/, ""));
8598
+ if (response !== void 0)
8599
+ await new Promise(
8600
+ (resolve, reject) => output.write(`${response}
8601
+ `, (error) => error ? reject(error) : resolve())
8602
+ );
8603
+ };
8604
+ for await (const chunk of input) {
8605
+ buffer += String(chunk);
8606
+ let end = buffer.indexOf("\n");
8607
+ while (end !== -1) {
8608
+ const line = buffer.slice(0, end);
8609
+ buffer = buffer.slice(end + 1);
8610
+ await respond(line);
8611
+ end = buffer.indexOf("\n");
8612
+ }
8613
+ }
8614
+ await respond(buffer);
8615
+ }
8616
+ var init_mcp_stdio = __esm({
8617
+ "src/surfaces/mcp_stdio.ts"() {
8618
+ }
8619
+ });
8620
+
8621
+ // src/surface/email_mcp_instructions.ts
8622
+ var emailMcpInstructions;
8623
+ var init_email_mcp_instructions = __esm({
8624
+ "src/surface/email_mcp_instructions.ts"() {
8625
+ 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
8626
  }
8194
8627
  });
8195
8628
 
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.
8629
+ // src/surface/email_mcp_options.ts
8630
+ function emailMcpOptions(context) {
8631
+ return {
8632
+ name: "ghostpaw-email",
8633
+ version: emailVersion,
8634
+ title: "Email",
8635
+ instructions: emailMcpInstructions,
8636
+ tools: emailMcpTools,
8637
+ context,
8638
+ annotations: (tool) => ({
8639
+ readOnlyHint: tool.readOnly ?? false,
8640
+ destructiveHint: ["mail_organize", "mail_compose"].includes(tool.name),
8641
+ idempotentHint: tool.readOnly ?? false,
8642
+ openWorldHint: true
8643
+ })
8644
+ };
8645
+ }
8646
+ var init_email_mcp_options = __esm({
8647
+ "src/surface/email_mcp_options.ts"() {
8648
+ init_version();
8649
+ init_email_mcp_instructions();
8650
+ init_email_surface_tools();
8651
+ }
8652
+ });
8229
8653
 
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
- });
8654
+ // src/surface/serve_email_mcp.ts
8655
+ var serve_email_mcp_exports = {};
8656
+ __export(serve_email_mcp_exports, {
8657
+ serveEmailMcp: () => serveEmailMcp
8658
+ });
8659
+ async function serveEmailMcp(options = {}) {
8660
+ let owned;
8661
+ const server = createMcpServer(
8662
+ emailMcpOptions(async () => {
8663
+ if (options.db) return options.db;
8664
+ owned = await openEmailDb(
8665
+ resolveEmailDbPath(options.dbPath === void 0 ? {} : { flag: options.dbPath })
8666
+ );
8667
+ return owned;
8668
+ })
8669
+ );
8670
+ try {
8671
+ await serveMcpStdio(server);
8672
+ } finally {
8673
+ owned?.close();
8674
+ }
8675
+ }
8676
+ var init_serve_email_mcp = __esm({
8677
+ "src/surface/serve_email_mcp.ts"() {
8678
+ init_mcp_server();
8679
+ init_mcp_stdio();
8680
+ init_email_mcp_options();
8681
+ init_open_email_db();
8682
+ init_resolve_email_db_path();
8235
8683
  }
8236
8684
  });
8237
8685
 
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
- ];
8686
+ // src/surfaces/skill_markdown.ts
8687
+ var skill_markdown_exports = {};
8688
+ __export(skill_markdown_exports, {
8689
+ renderSkillMarkdown: () => renderSkillMarkdown
8690
+ });
8691
+ function renderSkillMarkdown(spec, { referencesBase = "references" } = {}) {
8692
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(spec.name) || spec.name.length > 64)
8693
+ throw new Error("Invalid skill name");
8694
+ if (!spec.description.trim() || spec.description.length > 1024 || !spec.description.includes("Use when"))
8695
+ throw new Error("Invalid skill description");
8696
+ if (spec.compatibility && spec.compatibility.length > 500)
8697
+ throw new Error("Invalid compatibility");
8698
+ const lines = ["---", `name: ${spec.name}`, `description: ${JSON.stringify(spec.description)}`];
8699
+ for (const key of ["license", "compatibility"])
8700
+ if (spec[key]) lines.push(`${key}: ${JSON.stringify(spec[key])}`);
8701
+ if (spec.metadata) {
8702
+ lines.push("metadata:");
8703
+ for (const key of Object.keys(spec.metadata).sort())
8704
+ lines.push(` ${JSON.stringify(key)}: ${JSON.stringify(spec.metadata[key])}`);
8705
+ }
8706
+ lines.push(
8707
+ "---",
8708
+ "",
8709
+ `# ${spec.name}`,
8710
+ "",
8711
+ "## Install",
8712
+ "",
8713
+ "Linux/macOS (checks SHA256SUMS and installs ~/.local/bin/ghostpaw-email):",
8714
+ "",
8715
+ "```sh",
8716
+ "curl -fsSL https://raw.githubusercontent.com/GhostPawJS/email/main/install.sh | sh",
8717
+ "```",
8718
+ "",
8719
+ "Windows x64:",
8720
+ "",
8721
+ "```powershell",
8722
+ "irm https://raw.githubusercontent.com/GhostPawJS/email/main/install.ps1 | iex",
8723
+ "```",
8724
+ "",
8725
+ `Run tools as \`${spec.bin} ...\`; use \`~/.local/bin/${spec.bin}\` if it is not on PATH.`,
8726
+ "",
8727
+ spec.about,
8728
+ "",
8729
+ "## Calling tools",
8730
+ "",
8731
+ `MCP: connect to ${spec.server}, then call a tool by name with its JSON arguments.`,
8732
+ "",
8733
+ `CLI: \`${spec.bin} call <tool> '<JSON object>'\` or \`${spec.bin} <tool> --parameter value\`.`,
8734
+ "",
8735
+ `Inspect schemas with \`${spec.bin} describe <tool>\`. Use \`--db <path>\` to select a database.`,
8736
+ ""
8737
+ );
8738
+ for (const tool of spec.tools) {
8739
+ lines.push(
8740
+ `## ${tool.name}`,
8741
+ "",
8742
+ tool.description,
8743
+ "",
8744
+ `Use when: ${tool.whenToUse ?? ""}`,
8745
+ "",
8746
+ `Not for: ${tool.whenNotToUse ?? ""}`,
8747
+ "",
8748
+ tool.readOnly ? "Read-only." : `Writes: ${tool.sideEffects ?? "state"}.`,
8749
+ "",
8750
+ "Nested requirements apply within the parent for the selected action.",
8751
+ "",
8752
+ "| Parameter | Type | Required | Values / description |",
8753
+ "| --- | --- | --- | --- |"
8754
+ );
8755
+ 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", " ")} |`;
8756
+ const fields = (schema, prefix = "") => {
8757
+ const properties = Object.entries(schema.properties ?? {});
8758
+ for (const [name, property] of properties) {
8759
+ if (prefix && properties.length > 8 && !schema.required?.includes(name)) continue;
8760
+ lines.push(row(`${prefix}${name}`, property, schema.required?.includes(name) ?? false));
8761
+ const objects = [property, ...property.oneOf ?? []].filter((s4) => s4.properties);
8762
+ if (!objects.length)
8763
+ for (const branch of tool.inputSchema.oneOf ?? []) {
8764
+ const nested = branch.properties?.[name];
8765
+ if (nested?.properties) objects.push(nested);
8766
+ }
8767
+ const merged = { properties: {}, required: [] };
8768
+ for (const object of objects) {
8769
+ Object.assign(merged.properties ?? {}, object.properties);
8770
+ merged.required = [.../* @__PURE__ */ new Set([...merged.required ?? [], ...object.required ?? []])];
8771
+ }
8772
+ if (objects.length) fields(merged, `${prefix}${name}.`);
8773
+ }
8774
+ };
8775
+ fields(tool.inputSchema);
8776
+ lines.push("", "Examples:", "", "```sh");
8777
+ const actions = tool.inputSchema.properties?.action?.enum?.slice(0, 3) ?? [void 0];
8778
+ for (const action of actions) {
8779
+ const input = schemaExample(tool.inputSchema, action === void 0 ? {} : { action });
8780
+ lines.push(`${spec.bin} call ${tool.name} '${JSON.stringify(input)}'`);
8781
+ }
8782
+ lines.push("```");
8783
+ lines.push("");
8784
+ }
8785
+ lines.push(
8786
+ "## Workflow guides",
8787
+ "",
8788
+ ...spec.workflows.map(
8789
+ (workflow) => `- \`${spec.bin} skill ${workflow.name}\` ([${workflow.name}](${referencesBase}/${workflow.name}.md)): ${workflow.description}`
8790
+ ),
8791
+ "",
8792
+ "## Principles",
8793
+ "",
8794
+ ...spec.principles.map((principle) => `- ${principle}`),
8795
+ ""
8796
+ );
8797
+ if (spec.packageName)
8798
+ lines.push(
8799
+ "## Without the binary",
8800
+ "",
8801
+ `For npm-based environments (Node 24+): \`npx -y ${spec.packageName} ...\`.`,
8802
+ "",
8803
+ `Harnesses that embed it in code can import \`${spec.packageName}\` as a library.`,
8804
+ ""
8805
+ );
8806
+ return lines.join("\n");
8807
+ }
8808
+ var init_skill_markdown = __esm({
8809
+ "src/surfaces/skill_markdown.ts"() {
8810
+ init_schema_example();
8260
8811
  }
8261
8812
  });
8262
8813
 
@@ -8275,7 +8826,7 @@ var init_email_skill_spec = __esm({
8275
8826
  name: "email",
8276
8827
  description: "Read, search, compose, organize and synchronize email with a local SQLite cache. Use when managing email or searching cached messages.",
8277
8828
  license: "MIT",
8278
- compatibility: "Node.js 24 or newer. MCP stdio or email CLI.",
8829
+ compatibility: "Release binary ghostpaw-email (no runtime needed); MCP stdio via ghostpaw-email mcp.",
8279
8830
  bin: "ghostpaw-email",
8280
8831
  packageName: "@ghostpaw/email",
8281
8832
  server: "ghostpaw-email",
@@ -8298,6 +8849,8 @@ __export(email_cli_options_exports, {
8298
8849
  var emailCliOptions;
8299
8850
  var init_email_cli_options = __esm({
8300
8851
  "src/surface/email_cli_options.ts"() {
8852
+ init_cli_guide();
8853
+ init_email_skills();
8301
8854
  init_version();
8302
8855
  init_email_surface_tools();
8303
8856
  emailCliOptions = {
@@ -8324,7 +8877,19 @@ var init_email_cli_options = __esm({
8324
8877
  const { serveEmailMcp: serveEmailMcp2 } = await Promise.resolve().then(() => (init_serve_email_mcp(), serve_email_mcp_exports));
8325
8878
  await serveEmailMcp2(options.db === void 0 ? {} : { dbPath: options.db });
8326
8879
  },
8327
- skill: async () => {
8880
+ skill: async (args = []) => {
8881
+ const guides = [...emailSkills, cliGuide];
8882
+ if (args[0] === "--help" || args[0] === "-h")
8883
+ return "Usage: ghostpaw-email skill\n ghostpaw-email skill --list\n ghostpaw-email skill <guide>\n";
8884
+ if (args[0] === "--list")
8885
+ return `${guides.map((guide) => `${guide.name} ${guide.description.replace(/\s+/g, " ")}`).join("\n")}
8886
+ `;
8887
+ if (args.length) {
8888
+ const guide = guides.find((guide2) => guide2.name === args[0]);
8889
+ if (!guide || args.length !== 1)
8890
+ throw new Error(`unknown guide ${args.join(" ")}; run ghostpaw-email skill --list`);
8891
+ return guide.content;
8892
+ }
8328
8893
  const { renderSkillMarkdown: renderSkillMarkdown2 } = await Promise.resolve().then(() => (init_skill_markdown(), skill_markdown_exports));
8329
8894
  const { emailSkillSpec: emailSkillSpec2 } = await Promise.resolve().then(() => (init_email_skill_spec(), email_skill_spec_exports));
8330
8895
  return renderSkillMarkdown2(emailSkillSpec2);
@@ -9865,6 +10430,7 @@ async function runMain(cmd, opts = {}) {
9865
10430
  }
9866
10431
 
9867
10432
  // src/cli/index.ts
10433
+ init_cli_version();
9868
10434
  init_version();
9869
10435
 
9870
10436
  // src/cli/commands/account.ts
@@ -10465,8 +11031,8 @@ function parseAddress(raw2) {
10465
11031
  const match = /^(.+?)\s*<([^>]+)>$/.exec(raw2.trim());
10466
11032
  if (match) {
10467
11033
  const name = match[1]?.trim();
10468
- const address = match[2]?.trim() ?? "";
10469
- return name ? { name, address } : { address };
11034
+ const address2 = match[2]?.trim() ?? "";
11035
+ return name ? { name, address: address2 } : { address: address2 };
10470
11036
  }
10471
11037
  return { address: raw2.trim() };
10472
11038
  }
@@ -11045,7 +11611,7 @@ var main = defineCommand({
11045
11611
  meta: {
11046
11612
  name: "ghostpaw-email",
11047
11613
  version: emailVersion,
11048
- description: "Local-first email CLI powered by @ghostpaw/email."
11614
+ description: "Local-first email CLI powered by @ghostpaw/email.\nVersion output: --version --short or --version --json"
11049
11615
  },
11050
11616
  subCommands: {
11051
11617
  mcp: defineCommand({
@@ -11075,6 +11641,12 @@ async function runEmailCli(args = process.argv.slice(2)) {
11075
11641
  throw error;
11076
11642
  });
11077
11643
  }
11644
+ if (args.some((arg) => ["--version", "-V", "-v"].includes(arg))) {
11645
+ process.stdout.write(`${cliVersion(emailVersion, { args })}
11646
+ `);
11647
+ process.exitCode = 0;
11648
+ return;
11649
+ }
11078
11650
  let index = 0;
11079
11651
  while (index < args.length) {
11080
11652
  const token = args[index];
@@ -11099,4 +11671,6 @@ async function runEmailCli(args = process.argv.slice(2)) {
11099
11671
  }
11100
11672
 
11101
11673
  // src/cli.ts
11674
+ init_cli_version();
11675
+ markNpmEntry();
11102
11676
  await runEmailCli();