From 6a947e7b472d1c479f21a15e654ecf42836c9e92 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Mon, 23 Nov 2026 20:20:24 -0700 Subject: [PATCH] feat(direct-send): send-email --follows sends a follow-up in an earlier direct email's thread contact send-email --follows sends the email through Reply's send-direct-email-follow-up route instead of send-direct-email, as a follow-up in the thread of the earlier direct email the reference names. - The reference is checked before any call: email-, n from 1 with no leading zero and at most ten digits, as Reply spells it and as direct-send get takes it. Anything else is usage.reference, exit 2. - The message is {body} alone, since the follow-up goes under its thread's subject. A message carrying a subject is usage.message, exit 2, and says why; nothing is sent. - The other flags, the way the contact is found or imported, and the result are those of a plain send-email. - Reply's refusals of the email it follows map to follows.not_found, not_owned, other_contact, other_mailbox, never_sent, not_sent, too_early and not_placed, each read only under the status Reply publishes it with and only on this route. Every other refusal maps as on a plain send, and reply_code keeps Reply's code. - A 404 with no code of Reply's is follows.not_available: that Reply has no follow-up route. Nothing was sent, and nothing else is called. direct-send get and cancel add Reply's follows, the reference of the email a follow-up went in the thread of, or null, only when Reply gives it, so an older Reply prints as before. The failure codes a follow-up can end with are passed on as given, like every failure_code. The README and the reply-api skill say how to send a follow-up and what follows.not_available means. --- README.md | 28 +- skills/reply-adapter/reply-api/SKILL.md | 9 +- src/__tests__/operations/commands.test.ts | 44 +++- src/__tests__/operations/direct-send.test.ts | 245 ++++++++++++++++++ src/__tests__/operations/direct-sends.test.ts | 37 +++ src/__tests__/operations/program.test.ts | 27 ++ src/operations/commands.ts | 39 ++- src/operations/direct-send.ts | 88 ++++++- src/operations/direct-sends.ts | 6 + src/operations/stdin-input.ts | 8 + 10 files changed, 512 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index f97f648..436f3a0 100644 --- a/README.md +++ b/README.md @@ -210,6 +210,7 @@ prints JSON (indented; compact with `--json`) and says what happened in a stable | `reply contact delete ` | → `deleted` | | `reply contact opt-out ` | → `opted_out` | | `reply contact send-email --email-account-id N --message - [--track-links] [--track-opens]` | one email outside any sequence → `sent` | +| `reply contact send-email --email-account-id N --follows email- --message -` | a follow-up in an earlier direct email's thread, its `{body}` alone → `sent`, with its `reference` | | `reply contact linkedin-connect --linkedin-account-id N [--message -]` | a LinkedIn invitation, with or without a note → `sent` / `already_connected` | | `reply contact linkedin-message …` · `linkedin-inmail …` · `linkedin-voice …` | a LinkedIn message, an InMail, or an AI voice message spoken from a script → `sent` | | any direct send `… [--send-after ] [--schedule-id N] [--idempotency-key K]` | the send held until a moment, timed by a schedule, under a key of yours → `sent`, with its `reference` and `state` | @@ -352,6 +353,26 @@ it. Neither sends anything, and `reply_code` keeps Reply's own code, as on every # {"error":{"status":429,"code":"email.limit_reached",…,"reply_code":"contact.dailyLimitReached","retry_after":43200,"details":{"limit":"daily"}}} ``` +`contact send-email --follows ` sends the email as a follow-up in the thread of an earlier +direct email, named by the `reference` that send answered: `email-`, `n` from 1 with no leading +zero; any other form is refused before any call (`usage.reference`). The follow-up goes under its +thread's subject, so its message is `{body}` alone, and one carrying a `subject` is refused +(`usage.message`, exit 2). It goes to the contact and from the mailbox of the email it follows, takes +every other flag of a plain send, and its answer always carries Reply's `reference`. Reply refuses it, +and nothing is sent, when that email is none this account can see (`follows.not_found`) or a +teammate's this user may not act for (`follows.not_owned`), went to another contact or goes from +another mailbox (`follows.other_contact`, `follows.other_mailbox`), was cancelled or failed for good +(`follows.never_sent`), has not gone out yet while the follow-up would go at once (`follows.not_sent`: +give it a later `--send-after` or a `--schedule-id`), is due no earlier than the follow-up's +`--send-after` (`follows.too_early`), or went out but can no longer be found (`follows.not_placed`). +A Reply without follow-ups answers the route with a `404` and no code of its own: that is +`follows.not_available`, and nothing else is tried in its place. + +```sh +echo '{"body":"

Hi Ann, just bringing this back up.

"}' | reply contact send-email --contact-id 456 --email-account-id 12 --follows email-1001 --message - --send-after 2026-11-06T14:00:00Z +# {"status":"sent",…,"reference":"email-1002","send_after":"2026-11-06T14:00:00Z","state":"queued"} +``` + Every direct send also takes `--send-after `, `--schedule-id ` and `--idempotency-key `. Reply holds the send until the moment, given with its offset (`2026-11-03T14:00:00Z`, `2026-11-03T16:00:00+02:00`) and sent to Reply in UTC; a moment without an @@ -429,7 +450,12 @@ neither. So is `estimated_send_at`, read the same way as on the send but as of t not open within 30 days counted from `--send-after`, or from now once that has passed. `failure_reason` is a sentence for a person and never parsed; `failure_code` is Reply's code for the failure, the one to branch on. A failed send may carry no `failure_code`: it is then null, and -`failure_reason` is all Reply says of it. `direct-send cancel` of a send already cancelled answers +`failure_reason` is all Reply says of it. `follows` is added only when Reply gives it: the reference +of the email a follow-up went in the thread of, or null for a send that follows none. A follow-up +that failed may carry the `failure_code` `contact.followedSendNotSent` (that email had not gone out +when the follow-up was due), `contact.followedSendNeverSent` (it was cancelled or failed for good) or +`contact.followUpNotPlaced` (Reply could not find it to answer in its thread), passed on as given. +`direct-send cancel` of a send already cancelled answers it again. A send already gone out, failed or going out is `direct_send.already_sent`, `direct_send.already_failed` or `direct_send.already_sending`; the last is a LinkedIn send made for later that Reply is handing to the account's queue or that waits or runs there, even while diff --git a/skills/reply-adapter/reply-api/SKILL.md b/skills/reply-adapter/reply-api/SKILL.md index 3692b97..23c5809 100644 --- a/skills/reply-adapter/reply-api/SKILL.md +++ b/skills/reply-adapter/reply-api/SKILL.md @@ -6,7 +6,7 @@ description: > Use before calling any non-trivial v3 endpoint, when choosing an endpoint for a task, or when an API call fails and needs interpretation. metadata: - version: 1.5.1 + version: 1.6.0 pack: reply-adapter category: execution maturity: reviewed @@ -124,6 +124,11 @@ per-page `.md` fetches; the spec is large. "Nothing went out; sending again is safe" - while `directSend.dispatchInterrupted` is to be read as `unknown`, not `failed`: it may have gone out - "check before sending again" - so read the person's thread before any new send. + - **A follow-up in the thread:** `reply contact send-email --follows ` sends the email + in the thread of an earlier direct email, named by the `reference` that send answered + (`email-`), to its contact and from its mailbox; the message is `{body}` alone, since it goes + under the thread's subject. Its refusals are the `follows.*` codes its `--help` lists, and + `follows.not_available` says the account's Reply does not offer follow-ups: nothing was sent. - **A lost answer:** where an earlier try returned a `reference`, read it first with `reply direct-send get ` (from reply-cli 0.17.0), and let its state decide; repeat only when the read says nothing of the send. Reply keeps a key for a day, so a repeat goes under @@ -209,6 +214,8 @@ skill's confirmation rules — especially anything that sends messages or starts ## Changelog +- 1.6.0 (2026-11-23): *Direct sends* says how to send an email as a follow-up in an earlier direct + email's thread with `--follows`, and what `follows.not_available` means. - 1.5.1 (2026-11-05): *Conventions* and the error table say that a 429 naming a `reference` or saying a daily or weekly limit was reached is never resent and comes back at once as the refusal it is. diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index 67563b8..51d30f8 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -305,7 +305,9 @@ describe('operations/commands', ()=>{ const SENT_AT_AS_GIVEN = 'sentAtUtc as Reply gives them, each null when it gives none; the CLI adds no time of its own'; const DIRECT_SENDS: [string, string, string[], string][] = [ ['send-email', '--email-account-id', ['contact.not_found', ...IMPORT, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted', - 'contact.missing_variables', 'contact.rendering_failed', 'email.limit_reached', 'email.sending_disabled', 'schedule.not_found', 'schedule.no_slot', 'contact.time_zone_missing'], + 'contact.missing_variables', 'contact.rendering_failed', 'email.limit_reached', 'email.sending_disabled', 'follows.not_available', + 'follows.not_found', 'follows.not_owned', 'follows.other_contact', 'follows.other_mailbox', 'follows.never_sent', 'follows.not_sent', + 'follows.too_early', 'follows.not_placed', 'schedule.not_found', 'schedule.no_slot', 'contact.time_zone_missing'], 'sent_at is always null; the CLI adds none of its own'], ['linkedin-connect', '--linkedin-account-id', [...LINKEDIN, 'linkedin.not_connected', 'linkedin.limit_reached', 'linkedin.message_too_long', 'linkedin.missing_variables'], SENT_AT_AS_GIVEN], @@ -331,7 +333,7 @@ describe('operations/commands', ()=>{ { const c = sub(contact_command, name); expect(flags(c), name).toEqual([...CONTACT_FLAGS, account_flag, '--message', - ...(name === 'send-email' ? ['--track-links', '--track-opens'] : []), '--send-after', '--schedule-id', '--idempotency-key', + ...(name === 'send-email' ? ['--track-links', '--track-opens', '--follows'] : []), '--send-after', '--schedule-id', '--idempotency-key', '--use-contact-time-zone', '--no-use-contact-time-zone', ...(name === 'send-email' ? [] : ['--retry-window-minutes'])]); const text = help_of(c); const flat = text.replace(/\s+/g, ' '); @@ -416,6 +418,44 @@ describe('operations/commands', ()=>{ expect(flat, flat).toContain('email.sending_disabled (403) is a mailbox or team that cannot send direct emails now'); }); + it('send-email takes --follows, shows it in an example, and says what a follow-up takes and how each of its refusals reads', ()=>{ + const c = sub(contact_command, 'send-email'); + const text = help_of(c); + const flat = text.replace(/\s+/g, ' '); + const follows = c.options.find(o=>o.long === '--follows'); + expect(follows?.flags).toBe('--follows '); + expect(follows?.description).toContain('a follow-up in the thread of this earlier direct email'); + expect(c.options.find(o=>o.long === '--message')?.description).toContain('with --follows, {body} alone'); + expect(text, text).toContain('contact send-email --contact-id 456 --email-account-id 12 --follows email-1001 --message -'); + expect(flat, flat).toContain('--follows sends the email as a follow-up in the thread of an earlier direct email'); + expect(flat, flat).toContain('email- with n from 1 and no leading zero; any other form is refused before any call (usage.reference, exit 2)'); + expect(flat, flat).toContain('The follow-up goes under its thread\'s subject, so its message is {body} alone: a message with a subject is ' + + 'refused (usage.message, exit 2) and nothing is sent'); + expect(flat, flat).toContain('It goes to the contact and from the mailbox of the email it follows, and its answer always carries Reply\'s reference'); + for (const code of ['follows.not_found', 'follows.not_owned', 'follows.other_contact', 'follows.other_mailbox', 'follows.never_sent', + 'follows.not_sent', 'follows.too_early', 'follows.not_placed']) + { + expect(text, code).toContain(` ${code}\n`); + expect(flat.split('Errors')[0], code).toContain(code); + } + expect(flat, flat).toContain('follows.not_available: this Reply\'s follow-up route answers 404 with no code of Reply\'s, so it does not offer ' + + 'follow-ups; nothing else is tried in its place'); + expect(flat, flat).toContain('None of them sends anything, and each of the others keeps Reply\'s code in reply_code'); + expect(c.description(), c.description()).toContain('with --follows, in an earlier direct email\'s thread'); + }); + + it('direct-send get says when follows is given and which failure codes a follow-up may carry', ()=>{ + for (const name of ['get', 'cancel']) + { + const flat = help_of(sub(direct_send_command, name)).replace(/\s+/g, ' '); + expect(flat, name).toContain('follows is added only when Reply gives it: the reference of the earlier direct email a follow-up went in ' + + 'the thread of (send-email --follows), or null for a send that follows none'); + expect(flat, name).toContain('contact.followedSendNotSent (that email had not gone out when the follow-up was due), ' + + 'contact.followedSendNeverSent (it was cancelled or failed for good) or contact.followUpNotPlaced'); + expect(flat, name).toContain('like every failure_code, each is passed on as Reply gives it'); + } + }); + it('direct-send get says when the bounce members are given and what each holds', ()=>{ const flat = help_of(sub(direct_send_command, 'get')).replace(/\s+/g, ' '); expect(flat, flat).toContain('bounced, bounce_type and bounced_at are added only when Reply gives them'); diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index dd8951e..0e3ebb6 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -1325,3 +1325,248 @@ describe('a direct email Reply refuses for its limits', ()=>{ expect(await failure('linkedin-message', {body: TEXT}, LINKEDIN_OPTS)).toMatchObject({code: 'access.denied'}); }); }); + +describe('contact send-email --follows', ()=>{ + const FOLLOWS_OPTS: Direct_send_opts = {...EMAIL_OPTS, follows: 'email-1001'}; + const FOLLOW_UP = 'https://api/v3/contacts/456/send-direct-email-follow-up'; + const FOLLOW_UP_BODY = '

Hi Marta, just bringing this back up.

'; + const MESSAGE = {body: FOLLOW_UP_BODY}; + const QUEUED = {status: 'new', messageId: null, reference: 'email-1002', state: 'queued', sendAfter: '2026-11-06T14:00:00Z'}; + const lines = ()=>sent().map(r=>`${r.method} ${r.url}`); + const problem = (body: Record, status: number, headers: Record = {})=> + json(body, status, {'Content-Type': 'application/problem+json', ...headers}); + + it('sends the body alone through the follow-up route, naming the email it follows and no subject, and answers as a plain send does', async()=>{ + answer(json(QUEUED)); + expect(await run('send-email', MESSAGE, {...FOLLOWS_OPTS, sendAfter: '2026-11-06T14:00:00Z'})).toStrictEqual({ + status: 'sent', contact_id: 456, contact_created: false, message_id: null, sent_at: null, reply_status: 'new', + reference: 'email-1002', send_after: '2026-11-06T14:00:00Z', state: 'queued', + }); + expect(sent()).toEqual([{method: 'POST', url: FOLLOW_UP, + body: {emailAccountId: 12, body: FOLLOW_UP_BODY, follows: 'email-1001', sendAfter: '2026-11-06T14:00:00.000Z'}}]); + expect(sent()[0].body).not.toHaveProperty('subject'); + }); + + it('a follow-up Reply sent within the request adds its message id and the text as Reply filled it in', async()=>{ + answer(json({status: 'sent', messageId: '', reference: 'email-1002', state: 'sent', sendAfter: null, + renderedSubject: 'Re: Quick question', renderedBody: FOLLOW_UP_BODY})); + expect(await run('send-email', MESSAGE, FOLLOWS_OPTS)).toStrictEqual({ + status: 'sent', contact_id: 456, contact_created: false, message_id: '', sent_at: null, reply_status: 'sent', + reference: 'email-1002', state: 'sent', rendered_subject: 'Re: Quick question', rendered_body: FOLLOW_UP_BODY, + }); + expect(sent()[0].body).toStrictEqual({emailAccountId: 12, body: FOLLOW_UP_BODY, follows: 'email-1001'}); + }); + + it('takes the flags of a plain send as that send does: the moment, the schedule and its time zone, the tracking, and the key ' + + 'as a header', async()=>{ + answer(json(QUEUED)); + await run('send-email', MESSAGE, {...FOLLOWS_OPTS, sendAfter: '2026-11-06T16:00:00+02:00', scheduleId: '41', useContactTimeZone: false, + trackLinks: true, trackOpens: true, idempotencyKey: 'follow-up-456-1', retryWindowMinutes: '30'}); + expect(sent()[0].body).toStrictEqual({emailAccountId: 12, body: FOLLOW_UP_BODY, follows: 'email-1001', + sendAfter: '2026-11-06T14:00:00.000Z', scheduleId: 41, useContactTimeZone: false, trackLinks: true, trackOpens: true}); + expect((mock_fetch.mock.calls[0] as [string, RequestInit])[1].headers).toMatchObject({'Idempotency-Key': 'follow-up-456-1'}); + }); + + it('a mailbox id beyond 32 bits goes to Reply as the number given, and one not given is refused as on a plain send', async()=>{ + answer(json(QUEUED)); + await run('send-email', MESSAGE, {...FOLLOWS_OPTS, emailAccountId: '4294967296'}); + expect((sent()[0].body as {emailAccountId: unknown}).emailAccountId).toBe(4294967296); + mock_fetch.mockReset(); + expect(await failure('send-email', MESSAGE, {...FOLLOWS_OPTS, emailAccountId: undefined})).toMatchObject({code: 'usage.id', exit_code: 2}); + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('maps Reply\'s refusals of the email it follows, each definite, Reply\'s code kept in reply_code, with the ids it was given', async()=>{ + const cases: [number, string, string][] = [ + [404, 'contact.followedSendNotFound', 'follows.not_found'], + [403, 'contact.followedSendNotOwned', 'follows.not_owned'], + [400, 'contact.followedSendOtherContact', 'follows.other_contact'], + [400, 'contact.followedSendOtherMailbox', 'follows.other_mailbox'], + [409, 'contact.followedSendNeverSent', 'follows.never_sent'], + [409, 'contact.followedSendNotSent', 'follows.not_sent'], + [409, 'contact.followUpBeforeFollowedSend', 'follows.too_early'], + [409, 'contact.followUpNotPlaced', 'follows.not_placed'], + ]; + for (const [status, reply_code, code] of cases) + { + mock_fetch.mockReset(); + answer(problem({title: 'Refused', status, code: reply_code, detail: 'Reply\'s words.'}, status)); + const e = await failure('send-email', MESSAGE, FOLLOWS_OPTS); + expect(e, reply_code).toMatchObject({ + code, exit_code: 1, status, reply_code, detail: 'Reply\'s words.', ids: {contact_id: 456, email_account_id: 12}, + }); + expect((e as {title: string}).title, reply_code).toContain('nothing was sent'); + expect(shown(e), shown(e)).not.toContain('Marta'); + expect(lines(), reply_code).toEqual([`POST ${FOLLOW_UP}`]); + } + }); + + it('reads those codes only under the status Reply publishes each with, and only from the follow-up route', async()=>{ + const EMAIL = {subject: SUBJECT, body: BODY}; + const cases: [unknown, Direct_send_opts, number, string, string][] = [ + [MESSAGE, FOLLOWS_OPTS, 409, 'contact.followedSendNotFound', 'reply.refused'], + [MESSAGE, FOLLOWS_OPTS, 400, 'contact.followUpNotPlaced', 'reply.refused'], + [MESSAGE, FOLLOWS_OPTS, 404, 'contact.followedSendNotOwned', 'reply.refused'], + [EMAIL, EMAIL_OPTS, 404, 'contact.followedSendNotFound', 'reply.refused'], + [EMAIL, EMAIL_OPTS, 409, 'contact.followedSendNotSent', 'reply.refused'], + [EMAIL, EMAIL_OPTS, 403, 'contact.followedSendNotOwned', 'access.denied'], + ]; + for (const [message, opts, status, reply_code, code] of cases) + { + mock_fetch.mockReset(); + answer(problem({title: 'Refused', status, code: reply_code}, status)); + const label = `${opts.follows ?? 'plain'} ${status} ${reply_code}`; + expect(await failure('send-email', message, opts), label).toMatchObject({code, exit_code: 1, status, reply_code}); + expect(mock_fetch, label).toHaveBeenCalledTimes(1); + } + }); + + it('maps every other refusal as a plain send-email does, and nothing is sent', async()=>{ + const cases: [Response, string, string | undefined][] = [ + [problem({code: 'contact.notFound'}, 404), 'contact.not_found', 'contact.notFound'], + [problem({code: 'contact.emailAccountNotFound'}, 400), 'email_account.not_found', 'contact.emailAccountNotFound'], + [problem({code: 'contact.contactInBlackList'}, 400), 'contact.blacklisted', 'contact.contactInBlackList'], + [problem({code: 'contact.missingVariables', missingVariables: ['FirstName']}, 400), 'contact.missing_variables', 'contact.missingVariables'], + [problem({code: 'contact.renderingFailed'}, 400), 'contact.rendering_failed', 'contact.renderingFailed'], + [problem({code: 'contact.dailyLimitReached'}, 429, {'Retry-After': '3600'}), 'email.limit_reached', 'contact.dailyLimitReached'], + [problem({code: 'contact.activeContactsLimitReached'}, 429, {'Retry-After': '3600'}), 'email.limit_reached', + 'contact.activeContactsLimitReached'], + [problem({code: 'contact.emailAccountSendingDisabled'}, 403), 'email.sending_disabled', 'contact.emailAccountSendingDisabled'], + [problem({code: 'contact.scheduleNotFound'}, 404), 'schedule.not_found', 'contact.scheduleNotFound'], + [problem({code: 'contact.scheduleHasNoSlot'}, 409), 'schedule.no_slot', 'contact.scheduleHasNoSlot'], + [problem({code: 'contact.contactTimeZoneMissing'}, 409), 'contact.time_zone_missing', 'contact.contactTimeZoneMissing'], + [problem({code: 'contact.idempotencyKeyInUse'}, 409), 'idempotency_key.in_use', 'contact.idempotencyKeyInUse'], + [problem({code: 'contact.idempotencyKeyReused', reference: 'email-1002', state: 'queued'}, 409), 'idempotency_key.reused', + 'contact.idempotencyKeyReused'], + [problem({title: 'Validation failed', errors: [{pointer: '/subject', detail: 'A follow-up takes no subject.'}]}, 400), + 'reply.invalid_request', undefined], + [problem({code: 'contact.forbidden'}, 403), 'access.feature_unavailable', 'contact.forbidden'], + [problem({code: 'contact.somethingElse'}, 400), 'reply.refused', 'contact.somethingElse'], + ]; + for (const [res, code, reply_code] of cases) + { + mock_fetch.mockReset(); + answer(res); + const e = await failure('send-email', MESSAGE, {...FOLLOWS_OPTS, idempotencyKey: 'follow-up-456-1'}); + expect(e, code).toMatchObject({code, exit_code: 1, ids: {contact_id: 456, email_account_id: 12}}); + expect((e as {reply_code?: string}).reply_code, code).toBe(reply_code); + expect(lines(), code).toEqual([`POST ${FOLLOW_UP}`]); + } + }); + + it('an answer that may hide the follow-up is outcome.unknown (exit 3), made once, and says a repeat may send it twice', async()=>{ + const answers: [string, ()=>void][] = [ + ['lost answer', ()=>{ mock_fetch.mockRejectedValueOnce(lost_connection()); }], + ['503', ()=>answer(json({title: 'Service Unavailable'}, 503))], + ['500', ()=>answer(problem({title: 'Internal Server Error', status: 500}, 500))], + ['400 with neither a code nor errors[]', ()=>answer(problem({title: 'Internal error', status: 400}, 400))], + ['201', ()=>answer(json({}, 201))], + ['unreadable 200', ()=>answer(json('ok', 200))], + ]; + for (const [label, give] of answers) + { + mock_fetch.mockReset(); + give(); + const e = await failure('send-email', MESSAGE, FOLLOWS_OPTS); + expect(e, label).toMatchObject({code: 'outcome.unknown', exit_code: 3, ids: {contact_id: 456, email_account_id: 12}}); + const hint = (e as {hint?: string}).hint ?? ''; + expect(hint, `${label}: ${hint}`).toBe('The follow-up may have been sent; running the command again may send it twice.'); + expect(mock_fetch, label).toHaveBeenCalledTimes(1); + } + }); + + it('a 404 with no code of Reply\'s own is follows.not_available: this Reply has no follow-ups, nothing was sent, and nothing ' + + 'is called after it', async()=>{ + const bare: [string, ()=>Response][] = [ + ['empty', ()=>new Response(null, {status: 404})], + ['problem without a code', ()=>problem({title: 'Not Found', status: 404}, 404)], + ['html page', ()=>new Response('Not Found', {status: 404, headers: {'Content-Type': 'text/html'}})], + ['plain text', ()=>new Response('Not Found', {status: 404, headers: {'Content-Type': 'text/plain'}})], + ]; + for (const [label, res] of bare) + { + mock_fetch.mockReset(); + // Were anything called after the 404, a plain send among them, it would take this answer and the count would show it. + answer(res(), json({status: 'sent', messageId: ''})); + const e = await failure('send-email', MESSAGE, FOLLOWS_OPTS); + expect(e, label).toMatchObject({code: 'follows.not_available', status: 404, exit_code: 1, ids: {contact_id: 456, email_account_id: 12}}); + expect((e as {reply_code?: string}).reply_code, label).toBeUndefined(); + expect((e as {title: string}).title, label).toBe('This Reply does not offer follow-ups in an earlier email\'s thread, so nothing was sent.'); + expect(lines(), label).toEqual([`POST ${FOLLOW_UP}`]); + } + // The same 404 to a plain send stays what it was. + mock_fetch.mockReset(); + answer(problem({title: 'Not Found', status: 404}, 404)); + expect(await failure('send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS)).toMatchObject({code: 'reply.refused', status: 404}); + }); + + it('refuses a reference of any other form before stdin is read or any call is made', async()=>{ + const malformed = ['', 'email-0', 'email-01', 'email-', 'email', 'email-1a', 'email--1', 'email-12345678901', 'EMAIL-1', ' email-1', + 'email-1 ', 'email-1\n', 'linkedin-1', 'linkedin-scheduled-1', '1001', 'email-1001/cancel', '../email-1']; + const never = ()=>{ throw new Error('stdin was read'); }; + for (const follows of malformed) + { + const e = await handle_direct_send('send-email', {...FOLLOWS_OPTS, follows}, ctx(), {json: true}, never).catch((x: unknown)=>x); + expect(e, JSON.stringify(follows)).toMatchObject({code: 'usage.reference', exit_code: 2}); + expect((e as Error).message, JSON.stringify(follows)).toBe('--follows must be the reference of an earlier direct email: email-, n from 1.'); + } + expect(mock_fetch).not.toHaveBeenCalled(); + // The reference as Reply spells it, from 1 to ten digits, goes as given. + for (const follows of ['email-1', 'email-9999999999']) + { + mock_fetch.mockReset(); + answer(json(QUEUED)); + await run('send-email', MESSAGE, {...FOLLOWS_OPTS, follows}); + expect((sent()[0].body as {follows: unknown}).follows, follows).toBe(follows); + } + }); + + it('refuses a message that carries a subject, saying why, before any call and without repeating it', async()=>{ + for (const subject of [SUBJECT, '', null]) + { + for (const [input, opts] of [ + [{subject, body: FOLLOW_UP_BODY}, FOLLOWS_OPTS], + [{contact: {email: 'marta@example.com', first_name: 'Marta'}, message: {subject, body: FOLLOW_UP_BODY}}, + {...FOLLOWS_OPTS, contactId: undefined, contact: '-'}], + ] as [unknown, Direct_send_opts][]) + { + const e = await failure('send-email', input, opts); + const label = `${JSON.stringify(subject)} ${opts.contact ?? 'by id'}`; + expect(e, label).toMatchObject({code: 'usage.message', exit_code: 2}); + expect((e as Error).message, label).toBe('A follow-up takes no subject: it goes under its thread\'s subject, so the message is {body} alone.'); + expect(shown(e), shown(e)).not.toMatch(/marta|quick question|bringing/i); + } + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('refuses a body that is missing, blank or not text, and a field it does not know, as a plain send does', async()=>{ + for (const text of [{}, {body: ' '}, {body: 7}, {body: FOLLOW_UP_BODY, cc: 'marta@example.com'}, [MESSAGE], `not json, ${FOLLOW_UP_BODY}`]) + { + const e = await failure('send-email', text, FOLLOWS_OPTS); + expect(e, JSON.stringify(text)).toMatchObject({code: 'usage.message', exit_code: 2}); + expect(shown(e), shown(e)).not.toMatch(/marta|bringing/i); + } + for (const source of [JSON.stringify(MESSAGE), '@message.json', undefined]) + { + expect(await failure('send-email', MESSAGE, {...FOLLOWS_OPTS, message: source}), String(source)) + .toMatchObject({code: 'usage.message', exit_code: 2}); + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('a person given by their fields is looked up and imported as on a plain send, and the follow-up goes to the contact it ' + + 'created; one Reply already holds is refused before anything is sent', async()=>{ + const LOOKUP = 'GET https://api/v3/contacts?email=marta%40example.com&top=100&skip=0'; + const IMPORT = 'POST https://api/v3/contacts/import'; + const input = {contact: {email: 'marta@example.com', first_name: 'Marta'}, message: MESSAGE}; + const opts = {...FOLLOWS_OPTS, contactId: undefined, contact: '-'}; + answer(json({items: [], hasMore: false}), json({items: [{id: 457, status: 'created'}]}), json(QUEUED)); + expect(await run('send-email', input, opts)).toMatchObject({status: 'sent', contact_id: 457, contact_created: true, reference: 'email-1002'}); + expect(lines()).toEqual([LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-email-follow-up']); + mock_fetch.mockReset(); + answer(json({items: [{id: 456, email: 'marta@example.com'}], hasMore: false}), json(QUEUED)); + expect(await failure('send-email', input, opts)).toMatchObject({code: 'contact.already_held', exit_code: 1, ids: {contact_id: 456}}); + expect(lines()).toEqual([LOOKUP]); + }); +}); diff --git a/src/__tests__/operations/direct-sends.test.ts b/src/__tests__/operations/direct-sends.test.ts index 91fa865..b9df3af 100644 --- a/src/__tests__/operations/direct-sends.test.ts +++ b/src/__tests__/operations/direct-sends.test.ts @@ -118,6 +118,43 @@ describe('direct-send get', ()=>{ } }); + it('adds follows, the reference of the email a follow-up went in the thread of, as text or null and only when Reply gives it, ' + + 'to get and cancel', async()=>{ + const FOLLOW_UP = {...QUEUED, reference: 'email-1002'}; + const cases: [unknown, Record][] = [['email-1001', {follows: 'email-1001'}], [null, {follows: null}]]; + for (const fn of [get, cancel]) + { + for (const [follows, added] of cases) + { + mock_fetch.mockReset(); + answer(json({...FOLLOW_UP, follows})); + expect(await fn('email-1002'), JSON.stringify(follows)).toStrictEqual({ + reference: 'email-1002', channel: 'email', contact_id: 456, state: 'queued', send_after: '2026-11-03T14:00:00Z', + sent_at: null, message_id: null, failure_reason: null, cancelled_at: null, ...added, + }); + } + // A Reply before follow-ups gives none, and the send prints as it did before; a member of another shape is left out. + for (const odd of [undefined, 1001, ['email-1001'], {reference: 'email-1001'}]) + { + mock_fetch.mockReset(); + answer(json({...FOLLOW_UP, follows: odd})); + expect(await fn('email-1002'), JSON.stringify(odd)).not.toHaveProperty('follows'); + } + } + }); + + it('passes a failed follow-up\'s failure_code on as Reply gives it, translating none', async()=>{ + for (const failureCode of ['contact.followedSendNotSent', 'contact.followedSendNeverSent', 'contact.followUpNotPlaced']) + { + mock_fetch.mockReset(); + answer(json({...QUEUED, reference: 'email-1002', state: 'failed', failureReason: 'The letter this one follows did not go out.', + failureCode, follows: 'email-1001'})); + expect(await get('email-1002'), failureCode).toMatchObject({ + state: 'failed', failure_reason: 'The letter this one follows did not go out.', failure_code: failureCode, follows: 'email-1001', + }); + } + }); + it('gives missing_variables only as a list of names, and the others only as text: anything else is left out', async()=>{ for (const missing of [[], ['FirstName']]) { diff --git a/src/__tests__/operations/program.test.ts b/src/__tests__/operations/program.test.ts index c307b16..ff8ddaf 100644 --- a/src/__tests__/operations/program.test.ts +++ b/src/__tests__/operations/program.test.ts @@ -139,6 +139,33 @@ describe('the program', ()=>{ ]); }); + const FOLLOW_UP = ['--json', '-k', 'key-1', 'contact', 'send-email', '--contact-id', '456', '--email-account-id', '12', '--message', '-']; + + it('send-email --follows sends the body alone to the follow-up route; a Reply without that route exits 1 with ' + + 'follows.not_available, and nothing else is called', async()=>{ + pipe_stdin(JSON.stringify({body: 'Tuesday still works'})); + answer(new Response(null, {status: 404}), json({status: 'sent', messageId: ''})); + const {code, err} = await run_program([...FOLLOW_UP, '--follows', 'email-1001']); + expect(code).toBe(1); + expect(JSON.parse(err)).toMatchObject({error: {code: 'follows.not_available', status: 404, ids: {contact_id: 456, email_account_id: 12}}}); + expect(requests()).toEqual([{method: 'POST', url: 'https://api.reply.io/v3/contacts/456/send-direct-email-follow-up', + body: {emailAccountId: 12, body: 'Tuesday still works', follows: 'email-1001'}}]); + }); + + it('send-email --follows refuses a malformed reference, and a message with a subject, exit 2 before any request', async()=>{ + pipe_stdin(JSON.stringify({body: 'Tuesday still works'})); + const bad = await run_program([...FOLLOW_UP, '--follows', 'email-01']); + expect(bad.code).toBe(2); + expect(JSON.parse(bad.err)).toMatchObject({error: {code: 'usage.reference'}}); + vi.restoreAllMocks(); + pipe_stdin(JSON.stringify({subject: 'Hi Marta', body: 'Tuesday still works'})); + const {code, err} = await run_program([...FOLLOW_UP, '--follows', 'email-1001']); + expect(code).toBe(2); + expect(JSON.parse(err)).toMatchObject({error: {code: 'usage.message'}}); + expect(err, err).not.toMatch(PERSONAL); + expect(mock_fetch).not.toHaveBeenCalled(); + }); + const LATER_SEND = ['--json', '-k', 'key-1', 'contact', 'linkedin-message', '--contact-id', '456', '--linkedin-account-id', '34', '--message', '-']; diff --git a/src/operations/commands.ts b/src/operations/commands.ts index aeb81d1..2d8d155 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -421,18 +421,40 @@ const LINKEDIN_SCHEDULED = '--retry-window-minutes is how long Reply keeps t + 'direct sends but not yet the LinkedIn scheduler answers --schedule-id or --use-contact-time-zone on a LinkedIn send\n' + 'with errors[] naming the field (reply.invalid_request), and one that knows neither sends at once, as without them.\n'; +// The refusals of a follow-up sent with --follows, after Reply's own of the email it names. +const FOLLOWS_CODES = [ + 'follows.not_available', 'follows.not_found', 'follows.not_owned', 'follows.other_contact', 'follows.other_mailbox', + 'follows.never_sent', 'follows.not_sent', 'follows.too_early', 'follows.not_placed', +]; + +const FOLLOWS = '--follows sends the email as a follow-up in the thread of an earlier direct email: the reference\n' + + 'that send answered, email- with n from 1 and no leading zero; any other form is refused before any call\n' + + '(usage.reference, exit 2). The follow-up goes under its thread\'s subject, so its message is {body} alone: a message\n' + + 'with a subject is refused (usage.message, exit 2) and nothing is sent. It goes to the contact and from the mailbox of\n' + + 'the email it follows, and its answer always carries Reply\'s reference. follows.not_found is a reference Reply has no\n' + + 'direct email under that this account can see, and follows.not_owned a teammate\'s send this user may not act for.\n' + + 'follows.other_contact and follows.other_mailbox: that email went to another contact, or goes from another mailbox.\n' + + 'follows.never_sent: it was cancelled or failed for good. follows.not_sent: it has not gone out yet, so the follow-up\n' + + 'cannot go at once; give it a later --send-after or a --schedule-id. follows.too_early: --send-after is not later\n' + + 'than that email\'s own moment. follows.not_placed: that email went out, but Reply can no longer find it to answer in\n' + + 'its thread. follows.not_available: this Reply\'s follow-up route answers 404 with no code of Reply\'s, so it does not\n' + + 'offer follow-ups; nothing else is tried in its place. None of them sends anything, and each of the others keeps\n' + + 'Reply\'s code in reply_code.\n'; + time_zone_options(later_options(add_contact_options(contact_command.command('send-email'), true) .option('--email-account-id ', 'The mailbox to send from (see `account list`)') - .option('--message ', 'Only -: the email {subject, body} as JSON on stdin') + .option('--message ', 'Only -: the email {subject, body} as JSON on stdin; with --follows, {body} alone') .option('--track-links', 'Track the links in the email (off unless given)') - .option('--track-opens', 'Track the opens of the email (off unless given)'))) - .description('Send one email to a contact now, outside any sequence, from the mailbox you name') + .option('--track-opens', 'Track the opens of the email (off unless given)') + .option('--follows ', 'Send it as a follow-up in the thread of this earlier direct email (its reference, email-)'))) + .description('Send one email to a contact now, outside any sequence, from the mailbox you name; with --follows, in an earlier direct email\'s thread') .addHelpText('after', help( [`echo '{"subject":"Quick question","body":"

Hi Ann, does Tuesday work?

"}' | ${P} contact send-email --contact-id 456 --email-account-id 12 --message -`, - piped_send('send-email', ANN_EMAIL, '{"subject":"Quick question","body":"

Hi Ann

"}', '--email-account-id 12')], + piped_send('send-email', ANN_EMAIL, '{"subject":"Quick question","body":"

Hi Ann

"}', '--email-account-id 12'), + `echo '{"body":"

Hi Ann, just bringing this back up.

"}' | ${P} contact send-email --contact-id 456 --email-account-id 12 --follows email-1001 --message - --send-after 2026-11-06T14:00:00Z`], ['contact.not_found', ...IMPORT_CODES, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted', 'contact.missing_variables', 'contact.rendering_failed', 'email.limit_reached', 'email.sending_disabled', - ...SCHEDULE_CODES, ...KEY_CODES], true, + ...FOLLOWS_CODES, ...SCHEDULE_CODES, ...KEY_CODES], true, 'Result: {"status":"sent","contact_id","contact_created","message_id","sent_at","reply_status"}: sent means Reply\n' + 'accepted the email, and reply_status is Reply\'s own word for it (new or sent). message_id is Reply\'s messageId,\n' + 'null when it gives none. Reply\'s answer carries no time, so sent_at is always null; the CLI adds none of its own.\n' @@ -449,7 +471,7 @@ time_zone_options(later_options(add_contact_options(contact_command.command('sen + 'them; a send held for later has neither. contact.missing_variables names the variables Reply could not fill in\n' + 'details.missing_variables when Reply lists them, and contact.rendering_failed is a template Reply could not\n' + 'render, its message in detail. Neither sends anything.\n' - + LATER + SCHEDULED + SENT_TO('email', 'email'), + + FOLLOWS + LATER + SCHEDULED + SENT_TO('email', 'email'), SEND_TWICE('email'))) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); @@ -863,6 +885,11 @@ const DIRECT_SEND = 'Result: {"reference","channel","contact_id","state","send_a + 'the kind of the latest bounce, as given (hard, soft, mailboxFull, unknown, ...), and bounced_at is when it came.\n' + 'Reply leaves bounce_type and bounced_at null while bounced is false, and bounced_at null when the bounce carried no\n' + 'date; the CLI passes on what Reply gives and checks neither.\n' + + 'follows is added only when Reply gives it: the reference of the earlier direct email a follow-up went in the thread of\n' + + '(send-email --follows), or null for a send that follows none. A follow-up that failed may carry failure_code\n' + + 'contact.followedSendNotSent (that email had not gone out when the follow-up was due), contact.followedSendNeverSent\n' + + '(it was cancelled or failed for good) or contact.followUpNotPlaced (Reply could not find it to answer in its thread);\n' + + 'like every failure_code, each is passed on as Reply gives it.\n' + 'direct_send.not_found is a reference that Reply has no send for, a send of another team included.\n' + 'direct_send.not_owned is an email send made by a teammate this user may not act for.\n'; diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index 67e9b6d..c364b0a 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -2,6 +2,7 @@ import {PROGRAM_NAME} from '../config'; import {Operation_error, Unknown_outcome_error, UsageError, type Ids} from '../utils/errors'; import {parse_retry_after} from '../utils/client'; import {call_reply, expect_object, refusal, is_object, reply_code_of, detail_of, open_session, type Answer} from './call'; +import {route_missing} from './account-call'; import {parse_id, parse_int_in, parse_moment, parse_idempotency_key, LARGEST_SAFE_ID, type Op_globals} from './options'; import {read_contact_input, type Contact_flags, type Contact_ref} from './contact-input'; import {contact_not_found, find_contact_by_address, import_contact, type Channel, type Ensured} from './contacts'; @@ -13,7 +14,7 @@ type Direct_send_name = 'send-email' | 'linkedin-connect' | 'linkedin-message' | type Direct_send_opts = Contact_flags & { emailAccountId?: string; linkedinAccountId?: string; message?: string; sendAfter?: string; scheduleId?: string; idempotencyKey?: string; trackLinks?: boolean; trackOpens?: boolean; - useContactTimeZone?: boolean; retryWindowMinutes?: string; + useContactTimeZone?: boolean; retryWindowMinutes?: string; follows?: string; }; type Text = Record; @@ -23,6 +24,7 @@ type Direct_send = { fields: readonly string[]; // the text on stdin, every field required longest: Record; // the longest each field may be, where Reply publishes it text_optional?: boolean; // without --message nothing is read (an invitation without a note) + refused?: Record; // a field the text may not carry on this route, with the sentence that says why body: (account_id: number, text: Text | undefined) => Record; }; @@ -53,6 +55,29 @@ const DIRECT_SENDS: Record = { const CODE = 'usage.message'; +// send-email --follows: the email goes as a follow-up in the thread of an earlier direct email, through a route of its own. +// It goes under its thread's subject, so it takes a body alone, and Reply refuses a subject (400 at /subject); one given is +// refused here first, saying why, rather than read as an unknown field. +const EMAIL_FOLLOW_UP: Direct_send = { + path: 'send-direct-email-follow-up', what: 'follow-up', fields: ['body'], longest: {}, + refused: {subject: 'A follow-up takes no subject: it goes under its thread\'s subject, so the message is {body} alone.'}, + body: (id, t)=>({emailAccountId: id, body: t?.body}), +}; + +// The reference of an earlier direct email, spelled as Reply gives it and as direct-send get takes it: email-, n from 1, +// with no leading zero and at most ten digits. Nothing else is read from it. +const FOLLOWS = /^email-[1-9]\d{0,9}$/; + +const parse_follows = (raw: string): string=>{ + if (!FOLLOWS.test(raw)) + { + throw new UsageError('--follows must be the reference of an earlier direct email: email-, n from 1.', { + code: 'usage.reference', hint: 'The send-email that sent that email answered it as reference.', + }); + } + return raw; +}; + const required_id = (raw: string | undefined, flag: string, largest?: number): number=>{ if (raw === undefined) { @@ -71,7 +96,7 @@ const read_text = (name: Direct_send_name, send: Direct_send, source: string | u } const shape = `{${send.fields.map(f=>`"${f}":"…"`).join(',')}}`; const raw = read_stdin_object(source, { - flag: '--message', what: 'message', fields: send.fields, code: CODE, + flag: '--message', what: 'message', fields: send.fields, code: CODE, refused: send.refused, hint: `Pipe it in: echo '${shape}' | ${PROGRAM_NAME} contact ${name} … --message -`, }, read_stdin); const text: Text = {}; @@ -251,6 +276,43 @@ const KEY_REFUSALS: Record> = { email: {'contact.idempotencyKeyInUse': KEY_IN_USE, 'contact.idempotencyKeyReused': KEY_REUSED}, linkedin: {'directLinkedIn.idempotencyKeyInUse': KEY_IN_USE, 'directLinkedIn.idempotencyKeyReused': KEY_REUSED}, }; +// The follow-up route's refusals of the email it names in follows. Only that route answers them, so a plain send answering +// one of these codes falls to the usual mapping. Each one is definite: nothing was sent. +const FOLLOW_UP_REFUSALS: Record = { + 'contact.followedSendNotFound': { + status: 404, code: 'follows.not_found', title: 'Reply has no direct email under the --follows reference that this account can see, so nothing was sent.', + }, + 'contact.followedSendNotOwned': { + status: 403, code: 'follows.not_owned', title: 'The email --follows names is a teammate\'s send this user may not act for, so nothing was sent.', + }, + 'contact.followedSendOtherContact': { + status: 400, code: 'follows.other_contact', title: 'The email --follows names went to another contact, so nothing was sent.', + hint: 'A follow-up goes to the contact of the email it follows.', + }, + 'contact.followedSendOtherMailbox': { + status: 400, code: 'follows.other_mailbox', title: 'The email --follows names goes from another mailbox, so nothing was sent.', + hint: 'A follow-up goes from the mailbox of the email it follows: give that one in --email-account-id.', + }, + 'contact.followedSendNeverSent': { + status: 409, code: 'follows.never_sent', title: 'The email --follows names was cancelled or failed for good, so it has no thread; nothing was sent.', + }, + 'contact.followedSendNotSent': { + status: 409, code: 'follows.not_sent', title: 'The email --follows names has not gone out yet, so the follow-up cannot go at once; nothing was sent.', + hint: 'Give it a --send-after later than that email\'s own moment, or a --schedule-id; direct-send get reads where that email stands.', + }, + 'contact.followUpBeforeFollowedSend': { + status: 409, code: 'follows.too_early', title: 'The follow-up\'s --send-after is not later than the moment of the email it follows, so nothing was sent.', + hint: 'Give a --send-after later than that email\'s send_after.', + }, + 'contact.followUpNotPlaced': { + status: 409, code: 'follows.not_placed', + title: 'The email --follows names went out, but Reply can no longer find it to place the follow-up in its thread; nothing was sent.', + }, +}; +// A Reply without follow-ups: its route answers 404 with no code of Reply's own. Nothing else is tried in its place, a plain +// send included, so nothing was sent. +const follows_not_available = (): Operation_error=>new Operation_error('follows.not_available', + 'This Reply does not offer follow-ups in an earlier email\'s thread, so nothing was sent.', {status: 404}); // The routes that read and cancel a send by its reference answer under directSend: a reference this // account has no send for, a send it may not act on, and, to a cancel, a send already gone out or failed. const DIRECT_SEND_REFUSALS: Record = { @@ -304,7 +366,7 @@ const exception_of_send = (a: Answer): boolean=> const linkedin_exception = (a: Answer, by: Channel): boolean=> by === 'linkedin' && a.status === 400 && reply_code_of(a) === 'directLinkedIn.unknown'; -const refusal_of_send = (a: Answer, contact_id: number, by: Channel): Operation_error=>{ +const refusal_of_send = (a: Answer, contact_id: number, by: Channel, follow_up: boolean): Operation_error=>{ const reply_code = reply_code_of(a); if (exception_of_send(a) || linkedin_exception(a, by)) { @@ -312,6 +374,10 @@ const refusal_of_send = (a: Answer, contact_id: number, by: Channel): Operation_ status: a.status, reply_code, detail: detail_of(a), }); } + if (follow_up && route_missing(a)) + { + return follows_not_available(); + } if (a.status === 404 && (reply_code === 'contact.notFound' || reply_code === 'directLinkedIn.contactNotFound')) { return contact_not_found(contact_id, a); @@ -324,15 +390,16 @@ const refusal_of_send = (a: Answer, contact_id: number, by: Channel): Operation_ retry_after: parse_retry_after(a.headers['retry-after']) ?? undefined, details: {limit: limit.limit}, }); } - return known_refusal(a, REFUSALS) ?? known_refusal(a, TEMPLATE_REFUSALS[by]) ?? known_refusal(a, SENDING_REFUSALS[by]) + return (follow_up ? known_refusal(a, FOLLOW_UP_REFUSALS) : undefined) + ?? known_refusal(a, REFUSALS) ?? known_refusal(a, TEMPLATE_REFUSALS[by]) ?? known_refusal(a, SENDING_REFUSALS[by]) ?? known_refusal(a, KEY_REFUSALS[by]) ?? refusal(a, 'write'); }; // A send Reply refused after its row existed, or the send a reused key was taken for, comes with // Reply's reference, state and sendAfter: each one it gives as a string goes under details, beside // the refusal's own. The refusal's code and class are its own either way. -const send_refusal = (a: Answer, contact_id: number, by: Channel): Operation_error=>{ - const e = refusal_of_send(a, contact_id, by); +const send_refusal = (a: Answer, contact_id: number, by: Channel, follow_up: boolean): Operation_error=>{ + const e = refusal_of_send(a, contact_id, by, follow_up); const held = is_object(a.data) ? picked(HELD_KEYS, a.data) : {}; if (Object.keys(held).length > 0) { @@ -406,7 +473,10 @@ const already_held = (contact_id: number): Operation_error=> const handle_direct_send = async( name: Direct_send_name, opts: Direct_send_opts, ctx: Cli_context, g: Op_globals, read_stdin?: () => string, ): Promise=>{ - const send = DIRECT_SENDS[name]; + // Only send-email takes --follows; with it the email goes through the follow-up route instead of send-direct-email. + const follows = name === 'send-email' && opts.follows !== undefined ? parse_follows(opts.follows) : undefined; + const follow_up = follows !== undefined; + const send = follow_up ? EMAIL_FOLLOW_UP : DIRECT_SENDS[name]; const stdin = stdin_inputs({contact: opts.contact, message: opts.message}, { code: 'usage.stdin', hint: `Pipe both in one object: echo '{"contact":{…},"message":{…}}' | ${PROGRAM_NAME} contact ${name} --contact - … --message -`, }, read_stdin); @@ -488,7 +558,7 @@ const handle_direct_send = async( ids.contact_id = ensured.id; } sending = true; - const body = {...send.body(account_id, text), ...later}; + const body = {...send.body(account_id, text), ...(follow_up ? {follows} : {}), ...later}; const a = await call_reply(s, 'POST', `/v3/contacts/${ensured.id}/${send.path}`, 'write', body, headers); if (name === 'linkedin-connect' && a.status === 409 && reply_code_of(a) === 'directLinkedIn.alreadyConnected') { @@ -498,7 +568,7 @@ const handle_direct_send = async( } if (a.status !== 200) { - throw send_refusal(a, ensured.id, by); + throw send_refusal(a, ensured.id, by, follow_up); } print_result(result_of(name, ensured, expect_object(a, 'write')), g); } catch (e) { diff --git a/src/operations/direct-sends.ts b/src/operations/direct-sends.ts index 0c96111..b5fbb7d 100644 --- a/src/operations/direct-sends.ts +++ b/src/operations/direct-sends.ts @@ -48,6 +48,11 @@ const bounce_of = (body: Record): Record=>({ ...(typeof body.bouncedAt === 'string' || body.bouncedAt === null ? {bounced_at: body.bouncedAt} : {}), }); +// The reference of the earlier direct email a follow-up was sent in the thread of, as text, or null for a send that follows +// none, only when Reply gives it in that shape: a Reply before follow-ups gives none, and the send prints as it did before. +const follows_of = (body: Record): Record=> + typeof body.follows === 'string' || body.follows === null ? {follows: body.follows} : {}; + // A send as Reply holds it, under the CLI's names; one of its first fields that Reply leaves out is null. Its state is Reply's word, passed on as given, so a state the CLI does // not know yet reaches the caller instead of failing the read. failure_reason is a sentence for a person and failure_code // Reply's code for the same failure: neither is read here. @@ -62,6 +67,7 @@ const direct_send_of = (a: Answer, kind: 'read' | 'write'): Record; // a name the object may not carry here, with the sentence that says why }; // A person's text is read from stdin only, never from the argument list, which may be logged where @@ -32,6 +33,13 @@ const read_stdin_object = (source: string | undefined, o: Stdin_object_opts, rea { throw new UsageError(`The ${o.what} must be a JSON object: ${shape}.`, {code: o.code}); } + // A name refused here says why, rather than reading as unknown. + const refused = o.refused ?? {}; + const refused_field = Object.keys(value).find(k=>Object.prototype.hasOwnProperty.call(refused, k)); + if (refused_field !== undefined) + { + throw new UsageError(refused[refused_field], {code: o.code, hint: `Fields: ${o.fields.join(', ')}.`}); + } const unknown_field = Object.keys(value).find(k=>!o.fields.includes(k)); if (unknown_field !== undefined) {