coss-cli 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # coss-cli
2
2
 
3
- The command line for [coss.com](https://coss.com): sign in, send test emails, follow your environment's
4
- log, and receive its webhook events on your machine.
3
+ The command line for [coss.com](https://coss.com): sign in, send test emails and text messages, follow
4
+ your environment's log, and receive its webhook events on your machine.
5
5
 
6
6
  ```sh
7
7
  npm install -g coss-cli # or: npx coss-cli <command>
@@ -39,13 +39,14 @@ one downloaded with a browser needs `xattr -d com.apple.quarantine coss`.
39
39
  | `coss whoami` | The key in use, where it comes from, and its organization, project and environment. |
40
40
  | `coss profiles list` | The saved profiles: each one's environment, whether `coss login` created its key or it was pasted, and which is the default. |
41
41
  | `coss use <profile>` | Makes a saved profile the default. |
42
- | `coss init` | Sets the project in the current directory up: installs `coss` with its package manager (`--no-install` doesn't) and writes a new development key, approved in the dashboard and named after the project, to `.env.local` (Next.js) or `.env` (`--env-file` picks another). A key already there is kept unless `--force`. |
42
+ | `coss init` | Sets the project in the current directory up: installs `coss` with its package manager (`--no-install` doesn't) and writes a new development key, approved in the dashboard and named after the project, to `.env.local` (Next.js) or `.env` (`--env-file` picks another). A key already there is kept unless `--force`. `--agents` adds notes on coss.com for coding agents to the project's `AGENTS.md`. |
43
43
  | `coss open [page]` | Opens the environment's page in the dashboard: `overview`, `emails`, `logs`, `webhooks`, `api-keys`, `domains`, `billing`, … (`--print` prints the URL). |
44
44
  | `coss emails send` | A test email: `--to`, or `--simulate delivered\|bounced\|complained\|suppressed` for the mailbox simulator; `--template` with `--var name=value`; `--wait` follows it to its outcome (up to `--timeout`, 60 s). |
45
45
  | `coss emails list` | The environment's emails, newest first, with where each stands. Filter with `--to`, `--status`, `--recipient-status`, `-q`, `--category`, `--batch`, `--since`/`--until`; `--limit` (20). |
46
46
  | `coss emails get <id>` | An email: sender, recipients and their statuses, failure, tracking, attachments; `--text` or `--html` prints a body alone. |
47
47
  | `coss emails events <id>` | Its delivery events, with the receiving server's answers. |
48
48
  | `coss emails diagnose <id>` | Whether it was delivered and, if not, why and what to do (or `--to <address>` for the newest email to it). |
49
+ | `coss sms send` | A test text message: `--to +14155550123`, or `--simulate delivered\|invalid\|filtered\|opted-out\|reply` for the SMS simulator (sandbox keys); `--from` (default for sandbox keys `+14155550100`; live keys need one of your registered numbers), `--body`; `--wait` follows it to its outcome (and shows the simulator's reply). |
49
50
  | `coss logs tail` | New lines of the environment's log as they arrive: API requests, email events, webhook attempts. Filter with `--source`, `--level`, `--type`, `--status`, `-q`; `--since 15m` starts earlier; `--interval` sets the poll interval (2000 ms). |
50
51
  | `coss inbox` | The environment's inbound domain, then each email it receives as it arrives (`--since`, `--interval`). |
51
52
  | `coss inbox get <id>` | A received email: verdicts, attachments and its text (`--html`, `--headers`); `--raw > message.eml` saves the message as received. |
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { c as flushOutput, l as nodeIo, n as run } from "./run-BurjNVF6.js";
2
+ import { c as flushOutput, l as nodeIo, n as run } from "./run-B-0EIbmN.js";
3
3
  //#region src/cli.ts
4
4
  process.exitCode = await run(process.argv.slice(2), nodeIo());
5
5
  await flushOutput();
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { u as CURSOR_FIELDS, t as HELP, r as VERSION, s as defaultConfigDir, i as generateSecret, l as nodeIo, n as run, a as sign, o as signatureHeaders } from "./run-BurjNVF6.js";
1
+ export { u as CURSOR_FIELDS, t as HELP, r as VERSION, s as defaultConfigDir, i as generateSecret, l as nodeIo, n as run, a as sign, o as signatureHeaders } from "./run-B-0EIbmN.js";
@@ -43,7 +43,7 @@ function isTransient(error) {
43
43
  function apiError(doing, error) {
44
44
  const details = [error.message, ...(error.issues ?? []).map((issue) => ` ${issue.path}: ${issue.message}`)].join("\n");
45
45
  const request = error.request_id ? ` (request ${error.request_id})` : "";
46
- const hint = HINTS[error.type];
46
+ const hint = error.code === "insufficient_permissions" ? "This API key is restricted: `coss whoami` lists what it may do. Use a key with that permission." : HINTS[error.type];
47
47
  return new CliError(`${doing}: ${details}${request}${hint ? `\n${hint}` : ""}`);
48
48
  }
49
49
  function configPath(io) {
@@ -437,7 +437,7 @@ function shorten(text, max) {
437
437
  function minute(iso) {
438
438
  return iso ? iso.slice(0, 16).replace("T", " ") : "";
439
439
  }
440
- function statusStyle$3(status) {
440
+ function statusStyle$4(status) {
441
441
  if (status === "delivered" || status === "sent" || status === "received") return "green";
442
442
  if (status === "queued" || status === "scheduled" || status === "delivery_delayed" || status === "in_progress") return "yellow";
443
443
  if (status === "canceled") return "dim";
@@ -1469,11 +1469,11 @@ function isSimulatedOutcome(value) {
1469
1469
  }
1470
1470
  //#endregion
1471
1471
  //#region src/commands/emails.ts
1472
- const SANDBOX_FROM = "coss.com CLI <cli@example.com>";
1472
+ const SANDBOX_FROM$1 = "coss.com CLI <cli@example.com>";
1473
1473
  const DEFAULT_SUBJECT = "Test email from the coss.com CLI";
1474
1474
  const DEFAULT_TEXT = "Sent with `coss emails send`. https://coss.com/docs/cli";
1475
1475
  /** Recipient statuses after which nothing more is expected (unless waiting for a complaint). */
1476
- const SETTLED = /* @__PURE__ */ new Set([
1476
+ const SETTLED$1 = /* @__PURE__ */ new Set([
1477
1477
  "delivered",
1478
1478
  "bounced",
1479
1479
  "suppressed",
@@ -1490,17 +1490,17 @@ async function fileOrValue(value, file, flag) {
1490
1490
  throw new CliError(`Couldn't read ${file}: ${error.message}`);
1491
1491
  }
1492
1492
  }
1493
- function settled(email, simulate) {
1493
+ function settled$1(email, simulate) {
1494
1494
  if (email.status === "failed" || email.status === "canceled") return true;
1495
1495
  if (email.status === "queued" || email.status === "scheduled") return false;
1496
- return email.recipients.every((recipient) => simulate === "complained" && recipient.address === SIMULATED_OUTCOMES.complained ? recipient.status === "complained" : SETTLED.has(recipient.status));
1496
+ return email.recipients.every((recipient) => simulate === "complained" && recipient.address === SIMULATED_OUTCOMES.complained ? recipient.status === "complained" : SETTLED$1.has(recipient.status));
1497
1497
  }
1498
- async function waitForOutcome(context, coss, email, options) {
1498
+ async function waitForOutcome$1(context, coss, email, options) {
1499
1499
  const { io, out } = context;
1500
1500
  const deadline = io.now().getTime() + options.timeoutMs;
1501
1501
  let current = email;
1502
1502
  if (!out.json) out.info("Waiting for the outcome…");
1503
- while (!settled(current, options.simulate) && io.now().getTime() < deadline && !io.signal.aborted) {
1503
+ while (!settled$1(current, options.simulate) && io.now().getTime() < deadline && !io.signal.aborted) {
1504
1504
  await io.sleep(1e3, io.signal);
1505
1505
  const { data, error } = await coss.email.get(current.id, { signal: io.signal });
1506
1506
  if (error) {
@@ -1514,10 +1514,10 @@ async function waitForOutcome(context, coss, email, options) {
1514
1514
  return {
1515
1515
  email: current,
1516
1516
  events: data.data,
1517
- settled: settled(current, options.simulate)
1517
+ settled: settled$1(current, options.simulate)
1518
1518
  };
1519
1519
  }
1520
- function statusStyle$2(status) {
1520
+ function statusStyle$3(status) {
1521
1521
  if (status === "delivered" || status === "sent") return "green";
1522
1522
  if (status === "queued" || status === "scheduled" || status === "delivery_delayed") return "yellow";
1523
1523
  return "red";
@@ -1636,7 +1636,7 @@ async function emailsSend({ values, context }) {
1636
1636
  const credentials = await resolveCredentials(context);
1637
1637
  if (credentials.apiKey.startsWith("coss_live_") && !values.from) throw new UsageError("Live keys send from your own domain: pass --from you@your-domain.");
1638
1638
  const base = {
1639
- from: values.from ?? SANDBOX_FROM,
1639
+ from: values.from ?? SANDBOX_FROM$1,
1640
1640
  to,
1641
1641
  ...values.cc && { cc: addresses(values.cc) },
1642
1642
  ...values.bcc && { bcc: addresses(values.bcc) },
@@ -1677,7 +1677,7 @@ async function emailsSend({ values, context }) {
1677
1677
  }
1678
1678
  return 0;
1679
1679
  }
1680
- const outcome = await waitForOutcome(context, coss, email, {
1680
+ const outcome = await waitForOutcome$1(context, coss, email, {
1681
1681
  timeoutMs: timeoutS * 1e3,
1682
1682
  simulate
1683
1683
  });
@@ -1686,8 +1686,8 @@ async function emailsSend({ values, context }) {
1686
1686
  events: outcome.events
1687
1687
  });
1688
1688
  else {
1689
- out.line(`${outcome.email.id} ${out.style(statusStyle$2(outcome.email.status), outcome.email.status)}`);
1690
- for (const recipient of outcome.email.recipients) out.line(` ${recipient.address} ${out.style(statusStyle$2(recipient.status), recipient.status)}`);
1689
+ out.line(`${outcome.email.id} ${out.style(statusStyle$3(outcome.email.status), outcome.email.status)}`);
1690
+ for (const recipient of outcome.email.recipients) out.line(` ${recipient.address} ${out.style(statusStyle$3(recipient.status), recipient.status)}`);
1691
1691
  if (outcome.events.length > 0) out.line();
1692
1692
  for (const event of outcome.events) out.line(` ${out.style("dim", event.occurred_at)} ${event.type}${event.recipient ? ` ${event.recipient}` : ""}`);
1693
1693
  }
@@ -1979,7 +1979,7 @@ async function emailsGet({ values, positionals, context }) {
1979
1979
  }
1980
1980
  function printEmail(out, email) {
1981
1981
  const status = deliveryStatus(email);
1982
- out.line(`${out.style("bold", email.id)} ${out.style(statusStyle$3(status), status)}${email.sandbox ? out.style("dim", " (sandbox)") : ""}`);
1982
+ out.line(`${out.style("bold", email.id)} ${out.style(statusStyle$4(status), status)}${email.sandbox ? out.style("dim", " (sandbox)") : ""}`);
1983
1983
  field$1(out, "From", email.from);
1984
1984
  field$1(out, "Subject", email.subject);
1985
1985
  field$1(out, "Reply-To", email.reply_to.join(", "));
@@ -1991,7 +1991,7 @@ function printEmail(out, email) {
1991
1991
  field$1(out, "Sent", email.sent_at);
1992
1992
  if (email.failure) out.line(` ${out.style("dim", "Failure".padEnd(11))}${out.style("red", email.failure.code)}: ${printable(email.failure.message)}`);
1993
1993
  out.line();
1994
- for (const recipient of email.recipients) out.line(` ${recipient.type.padEnd(4)}${printable(recipient.address)} ${out.style(statusStyle$3(recipient.status), recipient.status)}`);
1994
+ for (const recipient of email.recipients) out.line(` ${recipient.type.padEnd(4)}${printable(recipient.address)} ${out.style(statusStyle$4(recipient.status), recipient.status)}`);
1995
1995
  const tracking = email.tracking;
1996
1996
  if (tracking.opens || tracking.clicks) {
1997
1997
  out.line();
@@ -2108,7 +2108,7 @@ async function emailsDiagnose({ values, positionals, context }) {
2108
2108
  }
2109
2109
  for (const recipient of diagnosis.recipients) {
2110
2110
  out.line();
2111
- out.line(` ${printable(recipient.address)} ${out.style(statusStyle$3(recipient.outcome), recipient.outcome)}`);
2111
+ out.line(` ${printable(recipient.address)} ${out.style(statusStyle$4(recipient.outcome), recipient.outcome)}`);
2112
2112
  out.line(` ${recipient.explanation}`);
2113
2113
  if (recipient.details) details(out, recipient.details);
2114
2114
  steps(out, recipient.next_steps, " ");
@@ -2172,7 +2172,7 @@ function pairs(values, flag) {
2172
2172
  return [pair.slice(0, index), pair.slice(index + 1)];
2173
2173
  }));
2174
2174
  }
2175
- function statusStyle$1(status) {
2175
+ function statusStyle$2(status) {
2176
2176
  return status === "succeeded" ? "green" : status === "pending" ? "yellow" : "red";
2177
2177
  }
2178
2178
  const appsList = defineCommand({
@@ -2585,7 +2585,7 @@ const HOOKS_COMMANDS = [
2585
2585
  ],
2586
2586
  row: (delivery) => [
2587
2587
  delivery.id,
2588
- out.style(statusStyle$1(delivery.status), delivery.status),
2588
+ out.style(statusStyle$2(delivery.status), delivery.status),
2589
2589
  String(delivery.attempt_count),
2590
2590
  delivery.last_error ?? (delivery.last_status_code === null ? "" : String(delivery.last_status_code)),
2591
2591
  delivery.endpoint_id,
@@ -2617,7 +2617,7 @@ const HOOKS_COMMANDS = [
2617
2617
  const { out } = context;
2618
2618
  if (!out.json) {
2619
2619
  const next = delivery.data.next_attempt_at ? `, next attempt ${when$1(delivery.data.next_attempt_at)}` : "";
2620
- out.line(`${delivery.data.id} ${out.style(statusStyle$1(delivery.data.status), delivery.data.status)} → ${delivery.data.endpoint_id}${out.style("dim", `${next}`)}`);
2620
+ out.line(`${delivery.data.id} ${out.style(statusStyle$2(delivery.data.status), delivery.data.status)} → ${delivery.data.endpoint_id}${out.style("dim", `${next}`)}`);
2621
2621
  }
2622
2622
  printList(out, list.data, {
2623
2623
  headings: [
@@ -3227,6 +3227,52 @@ function setEnvVar(text, name, value) {
3227
3227
  function removeEnvVar(text, name) {
3228
3228
  return text.replace(new RegExp(`^[ \\t]*(?:export[ \\t]+)?${name}[ \\t]*=.*(?:\\r?\\n|$)`, "gm"), "");
3229
3229
  }
3230
+ const NOTES_BEGIN = "<!-- BEGIN:coss -->";
3231
+ const NOTES_END = "<!-- END:coss -->";
3232
+ /**
3233
+ * What a coding agent working in the project should know about coss.com, for its AGENTS.md
3234
+ * (`--agents`). Keep it in step with the brief that opens https://coss.com/llms.txt
3235
+ * (apps/site/src/lib/llms.ts).
3236
+ */
3237
+ function agentNotes(envFile) {
3238
+ return `${NOTES_BEGIN}
3239
+ ## coss.com
3240
+
3241
+ This project uses [coss.com](https://coss.com) (email, SMS, webhooks) through its SDK.
3242
+
3243
+ - Docs: https://coss.com/llms.txt lists every page, and every docs page is Markdown at its URL plus
3244
+ \`.md\` (e.g. https://coss.com/docs/email/sending.md). API reference pages give each operation's
3245
+ parameters, request body, responses and errors. Read the page before writing code against it.
3246
+ - Develop and test with the development key (\`coss_test_…\`) in \`${envFile}\` as \`COSS_API_KEY\`:
3247
+ every API works and records what it would do, with events and webhooks, but nothing is
3248
+ delivered. A \`coss_live_…\` key there delivers for real: don't test with it, and never switch
3249
+ to one to try something (\`npx coss-cli init --force\` replaces it with a development key).
3250
+ - SDK methods return \`{ data, error }\` and don't throw for API failures: always check \`error\`.
3251
+ Webhook handlers verify each request with \`verifyWebhook\`, which throws on a bad signature.
3252
+ - After \`npx coss-cli login\`: \`npx coss-cli listen --forward-to localhost:3000/<path>\` forwards
3253
+ webhook events to a local handler, \`npx coss-cli trigger <event type>\` sends a test event, and
3254
+ \`npx coss-cli logs tail\` follows the API requests and events.
3255
+ ${NOTES_END}
3256
+ `;
3257
+ }
3258
+ /** `text` with the coss.com notes: an earlier copy replaced, else appended. */
3259
+ function setAgentNotes(text, notes) {
3260
+ const begin = text.indexOf(NOTES_BEGIN);
3261
+ const end = text.indexOf(NOTES_END, begin);
3262
+ if (begin !== -1 && end !== -1) {
3263
+ const after = text.slice(end + 17).replace(/^\r?\n/, "");
3264
+ return `${text.slice(0, begin)}${notes}${after}`;
3265
+ }
3266
+ if (text.trim() === "") return notes;
3267
+ return `${text.replace(/\s*$/, "")}\n\n${notes}`;
3268
+ }
3269
+ /** The project's agent instructions: AGENTS.md, else an existing CLAUDE.md, else a new AGENTS.md. */
3270
+ async function agentsFile(dir) {
3271
+ const agents = join(dir, "AGENTS.md");
3272
+ if (await exists$1(agents)) return agents;
3273
+ const claude = join(dir, "CLAUDE.md");
3274
+ return await exists$1(claude) ? claude : agents;
3275
+ }
3230
3276
  /** The project's name for the key: package.json's (without its scope), else the directory's. */
3231
3277
  function projectName(dir, pkg) {
3232
3278
  return (typeof pkg?.name === "string" ? pkg.name.replace(/^@[^/]+\//, "") : "") || basename(resolve(dir));
@@ -3234,7 +3280,7 @@ function projectName(dir, pkg) {
3234
3280
  const initCommand = defineCommand({
3235
3281
  name: "init",
3236
3282
  summary: "Set this project up: the SDK and a development API key",
3237
- description: "Sets up the project in the current directory: installs the coss package with the project's package manager, and writes a new development (sandbox) API key to its env file as COSS_API_KEY, created in the dashboard like `coss login`'s and named after the project. It is the project's key, not the CLI's: `coss login` signs the CLI in.\n\nAn env file that already has a key keeps it, unless --force.",
3283
+ description: "Sets up the project in the current directory: installs the coss package with the project's package manager, and writes a new development (sandbox) API key to its env file as COSS_API_KEY, created in the dashboard like `coss login`'s and named after the project. It is the project's key, not the CLI's: `coss login` signs the CLI in.\n\nAn env file that already has a key keeps it, unless --force. With --agents it also adds a short section on coss.com (docs, the development key, testing) to the project's AGENTS.md, or its CLAUDE.md when it has no AGENTS.md; running it again updates that section.",
3238
3284
  flags: {
3239
3285
  "env-file": {
3240
3286
  type: "string",
@@ -3249,6 +3295,10 @@ const initCommand = defineCommand({
3249
3295
  type: "boolean",
3250
3296
  description: "Replace a COSS_API_KEY the env file already has"
3251
3297
  },
3298
+ agents: {
3299
+ type: "boolean",
3300
+ description: "Add notes on coss.com for coding agents to the project's AGENTS.md (or CLAUDE.md)"
3301
+ },
3252
3302
  "no-browser": {
3253
3303
  type: "boolean",
3254
3304
  description: "Don't open a browser: open the link yourself, then paste the code it shows"
@@ -3274,8 +3324,10 @@ async function init({ values, context }) {
3274
3324
  const baseUrl = apiBaseUrl(io, profile);
3275
3325
  const dashboardUrl = dashboardBaseUrl(io, profile);
3276
3326
  let key = null;
3277
- if (existingKey && !values.force) out.info(`${shownFile} already has COSS_API_KEY: kept it (--force replaces it).`);
3278
- else {
3327
+ if (existingKey && !values.force) {
3328
+ out.info(`${shownFile} already has COSS_API_KEY: kept it (--force replaces it).`);
3329
+ if (existingKey.startsWith("coss_live_")) out.warn(`${shownFile}'s COSS_API_KEY is a live key: what you send with it is delivered. \`coss init --force\` replaces it with a development key.`);
3330
+ } else {
3279
3331
  const token = await browserLogin(context, dashboardUrl, {
3280
3332
  pasteCode: values["no-browser"] === true || isRemote(io),
3281
3333
  project: projectName(dir, pkg)
@@ -3315,12 +3367,20 @@ async function init({ values, context }) {
3315
3367
  if (code !== 0) throw new CliError(code === null ? `Couldn't run ${command}: install the coss package yourself.` : `\`${installed}\` failed (exit code ${code}): install the coss package yourself.`);
3316
3368
  if (!out.json) out.line(`${out.style("green", "✔")} Installed the coss package.`);
3317
3369
  }
3370
+ let notesFile = null;
3371
+ if (values.agents) {
3372
+ notesFile = await agentsFile(dir);
3373
+ const before = await readFile(notesFile, "utf8").catch(() => "");
3374
+ await writeFile(notesFile, setAgentNotes(before, agentNotes(shownFile)));
3375
+ if (!out.json) out.line(`${out.style("green", "✔")} ${before.includes(NOTES_BEGIN) ? "Updated" : "Added"} the coss.com notes for coding agents in ${relative(dir, notesFile)}.`);
3376
+ }
3318
3377
  if (out.json) {
3319
3378
  out.data({
3320
3379
  env_file: envFile,
3321
3380
  key,
3322
3381
  installed,
3323
- ignored_by_git: ignored
3382
+ ignored_by_git: ignored,
3383
+ agents_file: notesFile
3324
3384
  });
3325
3385
  return 0;
3326
3386
  }
@@ -3342,7 +3402,7 @@ Development keys never deliver email, but every send has its events and webhooks
3342
3402
  Next:
3343
3403
  coss listen --forward-to localhost:3000/webhooks receive webhook events locally
3344
3404
  coss logs tail follow the environment's log
3345
- https://coss.com/docs guides and the API reference`);
3405
+ https://coss.com/docs guides and the API reference${values.agents ? "" : "\n coss init --agents notes for coding agents in AGENTS.md"}`);
3346
3406
  return 0;
3347
3407
  }
3348
3408
  /** Whether git ignores the file: `null` outside a repository (or without git). */
@@ -3360,7 +3420,7 @@ async function ignoredByGit(io, dir, file) {
3360
3420
  //#endregion
3361
3421
  //#region src/version.ts
3362
3422
  /** The package version (`coss --version`, the forwarded requests' user agent). */
3363
- const VERSION = "0.2.0";
3423
+ const VERSION = "0.3.0";
3364
3424
  //#endregion
3365
3425
  //#region src/listen/forward.ts
3366
3426
  /** Posting an event to the local URL, as coss.com would post it to an endpoint. */
@@ -4432,6 +4492,207 @@ const RISK_COMMANDS = [
4432
4492
  })
4433
4493
  ];
4434
4494
  //#endregion
4495
+ //#region src/sms/simulate.ts
4496
+ /**
4497
+ * The SMS simulator: numbers whose outcome is known in advance in sandbox environments (coss.com's
4498
+ * fake SMS provider), never added to the suppression list. `coss sms send --simulate` sends to
4499
+ * them.
4500
+ *
4501
+ * Must match `SMS_SIMULATOR` in `packages/sms/src/schemas.ts` (the CLI can't import workspace
4502
+ * packages): change both together.
4503
+ */
4504
+ const SIMULATED_SMS_OUTCOMES = {
4505
+ /** Delivered. */
4506
+ delivered: "+15005550006",
4507
+ /** Failed: `invalid_number`. */
4508
+ invalid: "+15005550001",
4509
+ /** Undelivered: `carrier_filtered`. */
4510
+ filtered: "+15005550004",
4511
+ /** Failed: `opted_out`. */
4512
+ "opted-out": "+15005550009",
4513
+ /** Delivered, then a simulated reply arrives in the environment's received messages. */
4514
+ reply: "+15005550008"
4515
+ };
4516
+ function isSimulatedSmsOutcome(value) {
4517
+ return Object.hasOwn(SIMULATED_SMS_OUTCOMES, value);
4518
+ }
4519
+ //#endregion
4520
+ //#region src/commands/sms.ts
4521
+ const SANDBOX_FROM = "+14155550100";
4522
+ const DEFAULT_BODY = "Test message from the coss.com CLI";
4523
+ /** Statuses after which nothing more is expected. */
4524
+ const SETTLED = /* @__PURE__ */ new Set([
4525
+ "delivered",
4526
+ "undelivered",
4527
+ "failed",
4528
+ "canceled"
4529
+ ]);
4530
+ function settled(sms) {
4531
+ return SETTLED.has(sms.status);
4532
+ }
4533
+ async function waitForOutcome(context, coss, sms, options) {
4534
+ const { io, out } = context;
4535
+ const deadline = io.now().getTime() + options.timeoutMs;
4536
+ let current = sms;
4537
+ if (!out.json) out.info("Waiting for the outcome…");
4538
+ while (!settled(current) && io.now().getTime() < deadline && !io.signal.aborted) {
4539
+ await io.sleep(1e3, io.signal);
4540
+ const { data, error } = await coss.sms.get(current.id, { signal: io.signal });
4541
+ if (error) {
4542
+ if (io.signal.aborted) break;
4543
+ throw apiError("Couldn't read the message", error);
4544
+ }
4545
+ current = data;
4546
+ }
4547
+ if (io.signal.aborted) return {
4548
+ sms: current,
4549
+ events: [],
4550
+ replies: void 0,
4551
+ settled: settled(current)
4552
+ };
4553
+ const { data, error } = await coss.sms.listEvents(current.id, { signal: io.signal });
4554
+ if (error) {
4555
+ if (io.signal.aborted) return {
4556
+ sms: current,
4557
+ events: [],
4558
+ replies: void 0,
4559
+ settled: settled(current)
4560
+ };
4561
+ throw apiError("Couldn't read the message's events", error);
4562
+ }
4563
+ let replies;
4564
+ if (options.reply && current.status === "delivered" && !io.signal.aborted) {
4565
+ const received = await coss.sms.received.list({
4566
+ from: current.to,
4567
+ to: current.from,
4568
+ created_after: current.created_at
4569
+ }, { signal: io.signal });
4570
+ if (received.error && !io.signal.aborted) throw apiError("Couldn't read the received messages", received.error);
4571
+ replies = received.data?.data;
4572
+ }
4573
+ return {
4574
+ sms: current,
4575
+ events: data.data,
4576
+ replies,
4577
+ settled: settled(current)
4578
+ };
4579
+ }
4580
+ function statusStyle$1(status) {
4581
+ if (status === "delivered" || status === "sent") return "green";
4582
+ if (status === "queued" || status === "scheduled") return "yellow";
4583
+ return "red";
4584
+ }
4585
+ const smsSendCommand = defineCommand({
4586
+ name: "sms send",
4587
+ summary: "Send a test text message (--simulate filtered, --wait…)",
4588
+ description: "Sends a test text message from the API key's environment. Sandbox keys (coss_test_…) never reach a phone: they go through coss.com's simulated provider, with every event and webhook a real send has.",
4589
+ flags: {
4590
+ to: {
4591
+ type: "string",
4592
+ value: "<number>",
4593
+ description: "Recipient, in E.164 form (+14155550123)"
4594
+ },
4595
+ simulate: {
4596
+ type: "string",
4597
+ value: "<outcome>",
4598
+ choices: Object.keys(SIMULATED_SMS_OUTCOMES),
4599
+ description: "Send to the SMS simulator (sandbox keys only): delivered, invalid, filtered, opted-out, reply"
4600
+ },
4601
+ from: {
4602
+ type: "string",
4603
+ value: "<number>",
4604
+ description: "Sender, in E.164 form (default for sandbox keys: +14155550100; live keys need one of your organization's registered numbers)"
4605
+ },
4606
+ body: {
4607
+ type: "string",
4608
+ value: "<text>",
4609
+ description: "Default: \"Test message from the coss.com CLI\""
4610
+ },
4611
+ tag: {
4612
+ type: "string",
4613
+ multiple: true,
4614
+ value: "<name=value>",
4615
+ description: "A tag (repeatable)"
4616
+ },
4617
+ wait: {
4618
+ type: "boolean",
4619
+ description: "Follow the message until its outcome is known, then show its events (with --simulate reply, also the reply)"
4620
+ },
4621
+ timeout: {
4622
+ type: "string",
4623
+ value: "<seconds>",
4624
+ description: "How long --wait waits (default 60)"
4625
+ },
4626
+ json: {
4627
+ type: "boolean",
4628
+ description: "Print the message (and with --wait, its events) as JSON"
4629
+ }
4630
+ },
4631
+ run: smsSend
4632
+ });
4633
+ async function smsSend({ values, context }) {
4634
+ const { io, out } = context;
4635
+ const simulate = values.simulate;
4636
+ if (simulate !== void 0 && !isSimulatedSmsOutcome(simulate)) throw new UsageError(`--simulate takes ${Object.keys(SIMULATED_SMS_OUTCOMES).join(", ")}; got "${simulate}".`);
4637
+ if (simulate && values.to) throw new UsageError("Pass --to or --simulate, not both.");
4638
+ const to = simulate ? SIMULATED_SMS_OUTCOMES[simulate] : values.to;
4639
+ if (!to) throw new UsageError("Pass --to <number> or --simulate <outcome>.");
4640
+ const timeoutS = values.timeout === void 0 ? 60 : Number(values.timeout);
4641
+ if (!Number.isFinite(timeoutS) || timeoutS <= 0) throw new UsageError("--timeout takes a number of seconds.");
4642
+ const tags = pairs$1(values.tag ?? [], "tag").map(([name, value]) => ({
4643
+ name,
4644
+ value
4645
+ }));
4646
+ const credentials = await resolveCredentials(context);
4647
+ const live = credentials.apiKey.startsWith("coss_live_");
4648
+ if (live && simulate) throw new UsageError("--simulate needs a sandbox (coss_test_) key: live messages go to real carriers. Pass --to.");
4649
+ if (live && !values.from) throw new UsageError("Live keys send from one of your organization's numbers: pass --from +1….");
4650
+ const params = {
4651
+ from: values.from ?? SANDBOX_FROM,
4652
+ to,
4653
+ body: values.body ?? DEFAULT_BODY,
4654
+ ...tags.length > 0 && { tags }
4655
+ };
4656
+ const coss = clientFor(io, credentials);
4657
+ const { data: sms, error } = await coss.sms.send(params, { signal: io.signal });
4658
+ if (error) throw apiError("Couldn't send the message", error);
4659
+ if (!values.wait) {
4660
+ if (out.json) out.data(sms);
4661
+ else {
4662
+ out.line(`${out.style("green", "✔")} ${sms.id} ${sms.status} → ${sms.to}${sms.sandbox ? out.style("dim", " (sandbox)") : ""}`);
4663
+ out.info(out.style("dim", "Add --wait to follow it, or run `coss logs tail` to watch every event."));
4664
+ }
4665
+ return 0;
4666
+ }
4667
+ const outcome = await waitForOutcome(context, coss, sms, {
4668
+ timeoutMs: timeoutS * 1e3,
4669
+ reply: simulate === "reply"
4670
+ });
4671
+ if (out.json) out.data({
4672
+ ...outcome.sms,
4673
+ events: outcome.events,
4674
+ ...outcome.replies && { replies: outcome.replies }
4675
+ });
4676
+ else {
4677
+ out.line(`${outcome.sms.id} ${out.style(statusStyle$1(outcome.sms.status), outcome.sms.status)} → ${outcome.sms.to}`);
4678
+ if (outcome.sms.failure) out.line(` ${outcome.sms.failure.code}: ${outcome.sms.failure.message}`);
4679
+ if (outcome.events.length > 0) out.line();
4680
+ for (const event of outcome.events) {
4681
+ const failure = event.data.failure ? ` ${event.data.failure.code}` : "";
4682
+ out.line(` ${out.style("dim", event.occurred_at)} ${event.type}${failure}`);
4683
+ }
4684
+ for (const reply of outcome.replies ?? []) {
4685
+ out.line();
4686
+ out.line(` ${out.style("dim", reply.created_at)} reply from ${reply.from}: ${reply.body}`);
4687
+ }
4688
+ }
4689
+ if (!outcome.settled && !io.signal.aborted) {
4690
+ out.warn("Not every outcome arrived in time. Sends need the worker running (locally: `bun run dev`).");
4691
+ return 1;
4692
+ }
4693
+ return io.signal.aborted ? 130 : 0;
4694
+ }
4695
+ //#endregion
4435
4696
  //#region src/templates/files.ts
4436
4697
  /**
4437
4698
  * Templates as files: one folder per template (named by its alias, else its id) holding
@@ -5186,6 +5447,10 @@ const whoamiCommand = defineCommand({
5186
5447
  flags: {},
5187
5448
  run: whoami
5188
5449
  });
5450
+ function describeAccess(key) {
5451
+ if (key.access === "full") return "full";
5452
+ return `restricted: ${key.permissions.join(", ") || "nothing"}`;
5453
+ }
5189
5454
  async function whoami({ context }) {
5190
5455
  const { io, out } = context;
5191
5456
  const credentials = await resolveCredentials(context);
@@ -5202,6 +5467,7 @@ async function whoami({ context }) {
5202
5467
  }
5203
5468
  out.line(describeEnvironment(data));
5204
5469
  out.line(` Key ${data.api_key.name ?? "(unnamed)"} ${out.style("dim", data.api_key.id)}`);
5470
+ if (data.api_key.access) out.line(` Access ${describeAccess(data.api_key)}`);
5205
5471
  out.line(` From ${source}`);
5206
5472
  out.line(` API ${credentials.baseUrl}`);
5207
5473
  out.line(` Version ${data.organization.api_version}`);
@@ -5308,6 +5574,7 @@ const COMMANDS = [
5308
5574
  emailsGetCommand,
5309
5575
  emailsEventsCommand,
5310
5576
  emailsDiagnoseCommand,
5577
+ smsSendCommand,
5311
5578
  logsTailCommand,
5312
5579
  inboxCommand,
5313
5580
  inboxGetCommand,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "coss-cli",
3
- "version": "0.2.0",
4
- "description": "The coss.com command line: sign in, send test emails, tail your environment's log, and forward webhook events to localhost with `coss listen`.",
3
+ "version": "0.3.0",
4
+ "description": "The coss.com command line: sign in, send test emails and text messages, tail your environment's log, and forward webhook events to localhost with `coss listen`.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://coss.com/docs/cli",
7
7
  "repository": {
@@ -14,6 +14,7 @@
14
14
  "coss",
15
15
  "cli",
16
16
  "email",
17
+ "sms",
17
18
  "webhooks",
18
19
  "logs"
19
20
  ],
@@ -42,7 +43,7 @@
42
43
  "test": "bun test"
43
44
  },
44
45
  "dependencies": {
45
- "coss": "^0.7.0"
46
+ "coss": "^0.8.0"
46
47
  },
47
48
  "devDependencies": {
48
49
  "@arethetypeswrong/core": "0.18.5",