From 8c17ee0070af3f97ea3be0bede2cd0468bb9b068 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 16:46:02 -0700 Subject: [PATCH 01/24] feat: the direct sends take --send-after, --schedule-id and --idempotency-key A caller that times its own sends needs Reply to hold a send until a moment, within a schedule, and to tell a repeat of a send from a new one. Each flag is sent only when given: the moment as sendAfter in UTC, the schedule as scheduleId, the key as the Idempotency-Key header and never in the body. A moment without its offset is refused, since the CLI would have to choose a zone for it. The answer adds Reply's reference, sendAfter and state, each only when Reply gives it, so an answer without them prints what it printed before. status keeps its meaning, that Reply took the send; state says whether it has gone out. A key does not relax the hint after a lost answer: a Reply that ignores the header would send twice. --- src/__tests__/operations/commands.test.ts | 8 +- src/__tests__/operations/direct-send.test.ts | 100 +++++++++++++++++++ src/__tests__/operations/options.test.ts | 30 +++++- src/__tests__/operations/program.test.ts | 22 ++++ src/operations/call.ts | 9 +- src/operations/commands.ts | 31 ++++-- src/operations/direct-send.ts | 38 +++++-- src/operations/options.ts | 30 +++++- 8 files changed, 247 insertions(+), 21 deletions(-) diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index bc3afec..7902225 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -221,7 +221,7 @@ describe('operations/commands', ()=>{ for (const [name, account_flag, codes, sent_at] of DIRECT_SENDS) { const c = sub(contact_command, name); - expect(flags(c), name).toEqual([...CONTACT_FLAGS, account_flag, '--message']); + expect(flags(c), name).toEqual([...CONTACT_FLAGS, account_flag, '--message', '--send-after', '--schedule-id', '--idempotency-key']); const text = help_of(c); const flat = text.replace(/\s+/g, ' '); expect(text, text).toContain('--message -'); @@ -237,6 +237,12 @@ describe('operations/commands', ()=>{ expect(flat.includes('--email alone is refused (usage.contact)'), text).toBe(name !== 'send-email'); expect(flat, text).toContain(sent_at); expect(flat, text).toContain('read from stdin only'); + // A send for later: what status and state each say, and what an older Reply does with the flags. + expect(flat, text).toContain('status "sent" means Reply took the send; state, when Reply gives it, says whether it has gone ' + + 'out: queued or sending is not yet, then sent, failed or cancelled'); + expect(flat, text).toContain('direct-send get reads it later, and direct-send cancel stops one not yet sent'); + expect(flat, text).toContain('An answer without state comes from a Reply that does not know --send-after and --schedule-id'); + expect(flat, text).toContain('--idempotency-key goes as the Idempotency-Key header'); // Exactly the codes its endpoint publishes, then the shared ones, as the help lists them. const listed = text.split('\nErrors')[1].split('\nExit codes')[0].split('\n').slice(1).map(l=>l.trim()); expect(listed, name).toEqual([...codes, 'access.denied', 'access.feature_unavailable', 'rate_limited', 'reply.unavailable', diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index 9f6272a..13f8a78 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -620,3 +620,103 @@ describe('a direct send to a person given by their fields', ()=>{ } }); }); + +describe('a send for later', ()=>{ + const SENDS: [Direct_send_name, unknown, Direct_send_opts][] = [ + ['send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS], + ['linkedin-connect', {note: NOTE}, LINKEDIN_OPTS], + ['linkedin-message', {body: TEXT}, LINKEDIN_OPTS], + ['linkedin-inmail', {subject: SUBJECT, body: TEXT}, LINKEDIN_OPTS], + ['linkedin-voice', {script: SCRIPT}, LINKEDIN_OPTS], + ]; + const LATER = {sendAfter: '2026-11-03T16:00:00+02:00', scheduleId: '41', idempotencyKey: 'send-456-step-2'}; + const headers_of = (i: number): Record=> + (mock_fetch.mock.calls[i] as [string, RequestInit])[1].headers as Record; + const accepted = (name: Direct_send_name, extra: Record)=> + json(name === 'send-email' ? {status: 'new', messageId: null, ...extra} : {linkedInActivityId: 1042, ...extra}); + + it('each send carries the moment in UTC, the schedule and the key only when given, the key as a header and never in the body', async()=>{ + for (const [name, message, opts] of SENDS) + { + mock_fetch.mockReset(); + answer(accepted(name, {}), accepted(name, {})); + await run(name, message, {...opts, ...LATER}); + const body = sent()[0].body as Record; + expect(body.sendAfter, name).toBe('2026-11-03T14:00:00.000Z'); + expect(body.scheduleId, name).toBe(41); + expect(JSON.stringify(body), name).not.toContain('send-456-step-2'); + expect(headers_of(0)['Idempotency-Key'], name).toBe('send-456-step-2'); + await run(name, message, opts); + const plain = sent()[1].body as Record; + expect('scheduleId' in plain, name).toBe(false); + expect('sendAfter' in plain, name).toBe(false); + expect('Idempotency-Key' in headers_of(1), name).toBe(false); + } + }); + + it('adds reference, send_after and state to the answer, each only when Reply gives it, and keeps status as sent', async()=>{ + answer(accepted('send-email', {reference: 'email-1001', sendAfter: '2026-11-03T14:00:00Z', state: 'queued'})); + expect(await run('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...LATER})).toStrictEqual({ + status: 'sent', contact_id: 456, contact_created: false, message_id: null, sent_at: null, reply_status: 'new', + reference: 'email-1001', send_after: '2026-11-03T14:00:00Z', state: 'queued', + }); + mock_fetch.mockReset(); + answer(accepted('linkedin-message', {reference: 'linkedin-1042', state: 'sending', sendAfter: null})); + expect(await run('linkedin-message', {body: TEXT}, LINKEDIN_OPTS)).toStrictEqual({ + status: 'sent', contact_id: 456, contact_created: false, activity_id: 1042, sent_at: null, + reference: 'linkedin-1042', state: 'sending', + }); + }); + + it('an answer without them prints exactly what it prints today, even when the flags were given', async()=>{ + answer(accepted('linkedin-voice', {sentAtUtc: '2026-10-19T10:30:00Z'})); + expect(await run('linkedin-voice', {script: SCRIPT}, {...LINKEDIN_OPTS, ...LATER})).toStrictEqual({ + status: 'sent', contact_id: 456, contact_created: false, activity_id: 1042, sent_at: '2026-10-19T10:30:00Z', + }); + }); + + it('refuses a moment without its offset, a schedule id that is not one and a key Reply cannot take, before any call', async()=>{ + const cases: [Partial, string][] = [ + [{sendAfter: '2026-11-03T14:00:00'}, 'usage.date'], + [{sendAfter: '2026-11-03'}, 'usage.date'], + [{scheduleId: '0'}, 'usage.id'], + [{scheduleId: 'business'}, 'usage.id'], + [{idempotencyKey: ''}, 'usage.idempotency_key'], + [{idempotencyKey: 'k'.repeat(256)}, 'usage.idempotency_key'], + ]; + for (const [name, message, opts] of SENDS) + { + for (const [extra, code] of cases) + { + const e = await failure(name, message, {...opts, ...extra}); + expect(e, `${name} ${JSON.stringify(extra)}`).toMatchObject({code, exit_code: 2}); + } + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('a key does not make a lost answer safe to repeat: a Reply that ignores the header would send it twice', async()=>{ + mock_fetch.mockRejectedValueOnce(lost_connection()); + const e = await failure('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...LATER}); + expect(e).toMatchObject({code: 'outcome.unknown', exit_code: 3}); + expect((e as {hint?: string}).hint).toContain('may send it twice'); + }); + + it('a 404 with no code of Reply own stays reply.refused, status 404 and no reply code, an empty body or a problem without one', async()=>{ + const bare: [string, ()=>Response][] = [ + ['empty', ()=>new Response(null, {status: 404})], + ['problem', ()=>json({title: 'Not Found', status: 404}, 404, {'Content-Type': 'application/problem+json'})], + ]; + for (const [name, message, opts] of SENDS) + { + for (const [label, res] of bare) + { + mock_fetch.mockReset(); + answer(res()); + const e = await failure(name, message, {...opts, ...LATER}); + expect(e, `${name} ${label}`).toMatchObject({code: 'reply.refused', status: 404, exit_code: 1}); + expect((e as {reply_code?: string}).reply_code, `${name} ${label}`).toBeUndefined(); + } + } + }); +}); diff --git a/src/__tests__/operations/options.test.ts b/src/__tests__/operations/options.test.ts index aea2f2e..25c1397 100644 --- a/src/__tests__/operations/options.test.ts +++ b/src/__tests__/operations/options.test.ts @@ -1,5 +1,7 @@ import {describe, it, expect} from 'vitest'; -import {parse_id, parse_int_in, parse_iso, parse_choice, LARGEST_SAFE_ID} from '../../operations/options'; +import { + parse_id, parse_int_in, parse_iso, parse_moment, parse_idempotency_key, parse_choice, LARGEST_SAFE_ID, +} from '../../operations/options'; import {UsageError} from '../../utils/errors'; const usage_code = (fn: () => unknown): string | undefined=>{ @@ -60,6 +62,32 @@ describe('operations/options', ()=>{ } }); + it('parse_moment takes a date and time with its offset, as the same instant in UTC', ()=>{ + expect(parse_moment('2026-11-03T14:00:00Z', '--send-after')).toBe('2026-11-03T14:00:00.000Z'); + expect(parse_moment('2026-11-03T16:00:00+02:00', '--send-after')).toBe('2026-11-03T14:00:00.000Z'); + expect(parse_moment('2026-11-03T09:00-0500', '--since')).toBe('2026-11-03T14:00:00.000Z'); + expect(parse_moment('2026-11-03t14:00:00.25z', '--since')).toBe('2026-11-03T14:00:00.250Z'); + }); + + it('parse_moment refuses a date alone and a time without its offset, which the CLI would have to place in a zone of its own', ()=>{ + for (const bad of ['2026-11-03', '2026-11-03T14:00:00', '2026-11-03 14:00:00Z', 'tomorrow', '1', '2026-13-45T00:00:00Z']) + { + expect(usage_code(()=>parse_moment(bad, '--send-after')), bad).toBe('usage.date'); + } + expect(()=>parse_moment('2026-11-03T14:00:00', '--send-after')) + .toThrow('--send-after must be a date and time with its offset, e.g. 2026-11-03T14:00:00Z.'); + }); + + it('parse_idempotency_key takes 1 to 255 printable ASCII characters with no space at either end, as given', ()=>{ + expect(parse_idempotency_key('send-456-step-2')).toBe('send-456-step-2'); + expect(parse_idempotency_key('a b')).toBe('a b'); + expect(parse_idempotency_key('k'.repeat(255))).toBe('k'.repeat(255)); + for (const bad of ['', ' ', ' a', 'a ', 'k'.repeat(256), 'café', 'a\nb', 'a\tb']) + { + expect(usage_code(()=>parse_idempotency_key(bad)), JSON.stringify(bad)).toBe('usage.idempotency_key'); + } + }); + it('parse_choice accepts only the listed values', ()=>{ expect(parse_choice('sent', '--source', ['inbox', 'sent'] as const)).toBe('sent'); expect(parse_choice(undefined, '--source', ['inbox'] as const)).toBeUndefined(); diff --git a/src/__tests__/operations/program.test.ts b/src/__tests__/operations/program.test.ts index feb4fda..de5e5c3 100644 --- a/src/__tests__/operations/program.test.ts +++ b/src/__tests__/operations/program.test.ts @@ -139,6 +139,28 @@ describe('the program', ()=>{ ]); }); + const LATER_SEND = ['--json', '-k', 'key-1', 'contact', 'linkedin-message', '--contact-id', '456', '--linkedin-account-id', '34', + '--message', '-']; + + it('a send for later takes --send-after, --schedule-id and --idempotency-key: the first two in the body, the key as a header', async()=>{ + pipe_stdin(JSON.stringify({body: 'Thanks for connecting.'})); + answer(json({code: 'directLinkedIn.notConnected'}, 409)); + const {code} = await run_program([...LATER_SEND, + '--send-after', '2026-11-03T14:00:00Z', '--schedule-id', '41', '--idempotency-key', 'send-456-1']); + expect(code).toBe(1); + expect(requests()).toEqual([{method: 'POST', url: 'https://api.reply.io/v3/contacts/456/send-direct-linkedin-message', + body: {linkedInAccountId: 34, message: 'Thanks for connecting.', sendAfter: '2026-11-03T14:00:00.000Z', scheduleId: 41}}]); + expect((mock_fetch.mock.calls[0] as [string, RequestInit])[1].headers).toMatchObject({'Idempotency-Key': 'send-456-1'}); + }); + + it('a send for later at a moment without its offset exits 2 before any request', async()=>{ + pipe_stdin(JSON.stringify({body: 'Thanks for connecting.'})); + const {code, err} = await run_program([...LATER_SEND, '--send-after', '2026-11-03T14:00:00']); + expect(code).toBe(2); + expect(JSON.parse(err)).toMatchObject({error: {code: 'usage.date'}}); + expect(mock_fetch).not.toHaveBeenCalled(); + }); + it('a send to a person Reply already holds exits 1, sends nothing, and names the contact', async()=>{ pipe_stdin(JSON.stringify({contact: {email: 'marta@example.com', first_name: 'Marta'}, message: {subject: 'Hi Marta', body: 'Tuesday works'}})); diff --git a/src/operations/call.ts b/src/operations/call.ts index 98c32e1..46c0a87 100644 --- a/src/operations/call.ts +++ b/src/operations/call.ts @@ -37,10 +37,13 @@ const detail_of = (a: Answer): string | undefined=>{ // One call to Reply for an operation. Every HTTP status comes back as an Answer for the command // to read. If Reply can't be reached, nothing happened, so that becomes reply.unavailable. A -// write whose answer was lost passes through as outcome.unknown. -const call_reply = async(s: Op_session, method: string, path: string, kind: Call_kind, body?: unknown): Promise=>{ +// write whose answer was lost passes through as outcome.unknown. Headers given here are this call's +// own, on top of the session's. +const call_reply = async( + s: Op_session, method: string, path: string, kind: Call_kind, body?: unknown, headers: Record = {}, +): Promise=>{ try { - const r = await request_raw(s.api_base, s.token, method, path, body, {headers: s.headers, kind}); + const r = await request_raw(s.api_base, s.token, method, path, body, {headers: {...s.headers, ...headers}, kind}); return {status: r.status, data: r.data, headers: r.response_headers}; } catch (e) { if (e instanceof RuntimeError) diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 9f6db12..88fe494 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -290,15 +290,29 @@ const SENT_TO = (by: 'email' | 'linkedin', what: string): string=>CONTACT_FORMS + '--contact-id it is always false; in both cases a successful answer says the send was made.\n' + (by === 'email' ? '' : LINKEDIN_URL_NEEDED) + STDIN_PAIR('message'); +// The flags of a send for later, the same on every direct send. +const later_options = (c: Command): Command=>c + .option('--send-after ', 'Send at or after this moment, given with its offset (e.g. 2026-11-03T14:00:00Z)') + .option('--schedule-id ', 'The sending schedule Reply times the send by (see `schedule list`)') + .option('--idempotency-key ', 'Your own key for this send, sent as the Idempotency-Key header'); + +const LATER = 'With --send-after Reply holds the send until that moment, given with its offset and sent to Reply in UTC; a moment\n' + + 'without an offset is refused (usage.date). --schedule-id names the sending schedule Reply times the send by. The answer\n' + + 'then adds Reply\'s reference, send_after and state, each only when Reply gives it: status "sent" means Reply took the\n' + + 'send; state, when Reply gives it, says whether it has gone out: queued or sending is not yet, then sent, failed or\n' + + 'cancelled. direct-send get reads it later, and direct-send cancel stops one not yet sent. An\n' + + 'answer without state comes from a Reply that does not know --send-after and --schedule-id: it sent at once, as\n' + + 'without them. --idempotency-key goes as the Idempotency-Key header, never in the body.\n'; + // One send's example with the person and the text both on stdin. const piped_send = (command: string, contact: string, message: string, flags: string): string=> `echo '{"contact":${contact},"message":${message}}' | ${P} contact ${command} --contact - ${flags} --message -`; const ANN_EMAIL = '{"email":"ann@example.com","first_name":"Ann"}'; const ANN_PROFILE = '{"linkedin_url":"https://www.linkedin.com/in/ann-example","first_name":"Ann"}'; -add_contact_options(contact_command.command('send-email'), true) +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')) .description('Send one email to a contact now, outside any sequence, from the mailbox you name') .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 -`, @@ -307,9 +321,9 @@ add_contact_options(contact_command.command('send-email'), 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' - + 'The email is read from stdin only, so its text never sits in the argument list. The body is HTML. Reply sends a\n' - + 'direct email at once, outside the mailbox\'s daily limit and sending delay.\n' - + SENT_TO('email', 'email'), + + 'The email is read from stdin only, so its text never sits in the argument list. The body is HTML. Without\n' + + '--send-after, Reply sends a direct email at once, outside the mailbox\'s daily limit and sending delay.\n' + + LATER + SENT_TO('email', 'email'), SEND_TWICE('email'))) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); @@ -332,11 +346,12 @@ const linkedin_send = ( name: Exclude, description: string, message: string, examples: string[], codes: string[], extra: string, what: string, ): void=>{ - add_contact_options(contact_command.command(name), true) + later_options(add_contact_options(contact_command.command(name), true) .option('--linkedin-account-id ', 'The LinkedIn account to send from (see `account list`)') - .option('--message ', `Only -: the ${message} as JSON on stdin`) + .option('--message ', `Only -: the ${message} as JSON on stdin`)) .description(description) - .addHelpText('after', help(examples, [...LINKEDIN_SEND_CODES, ...codes], true, extra + SENT_TO('linkedin', what), SEND_TWICE(what))) + .addHelpText('after', help(examples, [...LINKEDIN_SEND_CODES, ...codes], true, extra + LATER + SENT_TO('linkedin', what), + SEND_TWICE(what))) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); await handle_direct_send(name, cmd.opts(), ctx, g); diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index 19fe209..9945893 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -2,7 +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, reply_code_of, detail_of, open_session, type Answer} from './call'; -import {parse_id, LARGEST_SAFE_ID, type Op_globals} from './options'; +import {parse_id, 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'; import {read_stdin_object, stdin_inputs} from './stdin-input'; @@ -10,7 +10,10 @@ import {print_result, with_ids} from './result'; import type {Cli_context} from '../context'; type Direct_send_name = 'send-email' | 'linkedin-connect' | 'linkedin-message' | 'linkedin-inmail' | 'linkedin-voice'; -type Direct_send_opts = Contact_flags & {emailAccountId?: string; linkedinAccountId?: string; message?: string}; +type Direct_send_opts = Contact_flags & { + emailAccountId?: string; linkedinAccountId?: string; message?: string; + sendAfter?: string; scheduleId?: string; idempotencyKey?: string; +}; type Text = Record; type Direct_send = { @@ -166,11 +169,19 @@ const send_refusal = (a: Answer, contact_id: number): Operation_error=>{ const positive_integer = (v: unknown): number | null=> typeof v === 'number' && Number.isSafeInteger(v) && v > 0 ? v : null; +// What Reply says of the send itself, each only when it gives it: the reference that names the send +// for direct-send get and cancel, the moment it was accepted for, and whether it has gone out. An +// answer without them is printed as it always was. +const LATER_KEYS: [string, string][] = [['reference', 'reference'], ['sendAfter', 'send_after'], ['state', 'state']]; + +const later_of = (sent: Record): Record=> + Object.fromEntries(LATER_KEYS.filter(([from])=>typeof sent[from] === 'string').map(([from, to])=>[to, sent[from]])); + // What the CLI answers for a send Reply took: the contact it went to, as the add commands name it, so // a caller can keep its id. Neither adds a time of its own: Reply's answer to a direct email carries // none, and a LinkedIn send's sentAtUtc is given as Reply gives it. -const result_of = (name: Direct_send_name, contact: Ensured, sent: Record): Record=> - name === 'send-email' +const result_of = (name: Direct_send_name, contact: Ensured, sent: Record): Record=>({ + ...(name === 'send-email' ? { status: 'sent', contact_id: contact.id, contact_created: contact.created, message_id: typeof sent.messageId === 'string' ? sent.messageId : null, @@ -181,7 +192,9 @@ const result_of = (name: Direct_send_name, contact: Ensured, sent: Record = {}; + if (opts.sendAfter !== undefined) + { + later.sendAfter = parse_moment(opts.sendAfter, '--send-after'); + } + if (opts.scheduleId !== undefined) + { + later.scheduleId = parse_id(opts.scheduleId, '--schedule-id'); + } + const headers: Record = opts.idempotencyKey === undefined + ? {} : {'Idempotency-Key': parse_idempotency_key(opts.idempotencyKey)}; const s = await open_session(ctx, g); let sending = false; try { @@ -263,7 +288,8 @@ const handle_direct_send = async( ids.contact_id = ensured.id; } sending = true; - const a = await call_reply(s, 'POST', `/v3/contacts/${ensured.id}/${send.path}`, 'write', send.body(account_id, text)); + const body = {...send.body(account_id, text), ...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') { // Nothing was sent, and nothing needs to be: the contact is already a connection. diff --git a/src/operations/options.ts b/src/operations/options.ts index ed96167..7d6a330 100644 --- a/src/operations/options.ts +++ b/src/operations/options.ts @@ -67,7 +67,33 @@ const parse_iso = (raw: string, label: string): string=>{ return new Date(at).toISOString(); }; -const parse_choice = (raw: string | undefined, label: string, allowed: readonly T[]): T | undefined=>{ +const MOMENT = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)(Z|[+-]\d{2}:?\d{2})$/i; + +// A moment Reply acts at, such as a send's: a date and time with its offset, sent as the same instant +// in UTC. Without an offset the CLI would have to choose a zone for it, so one is refused. +const parse_moment = (raw: string, label: string): string=>{ + const m = MOMENT.exec(raw.trim()); + const at = m === null ? NaN : Date.parse(`${m[1]}T${m[2]}${m[3].toUpperCase().replace(/^([+-]\d{2})(\d{2})$/, '$1:$2')}`); + if (isNaN(at)) + { + throw new UsageError(`${label} must be a date and time with its offset, e.g. 2026-11-03T14:00:00Z.`, {code: 'usage.date', hint: `Got: ${raw}`}); + } + return new Date(at).toISOString(); +}; + +// An Idempotency-Key header as Reply takes one: 1 to 255 printable ASCII characters. A space at +// either end is refused rather than trimmed away by the header on its way out. +const parse_idempotency_key = (raw: string): string=>{ + if (!/^[\x21-\x7e](?:[\x20-\x7e]{0,253}[\x21-\x7e])?$/.test(raw)) + { + throw new UsageError('--idempotency-key must be 1 to 255 printable ASCII characters, with no space at either end.', { + code: 'usage.idempotency_key', + }); + } + return raw; +}; + +const parse_choice =(raw: string | undefined, label: string, allowed: readonly T[]): T | undefined=>{ if (raw === undefined) { return undefined; @@ -80,6 +106,6 @@ const parse_choice = (raw: string | undefined, label: string, }; export { - read_op_globals, parse_id, parse_int_in, parse_iso, parse_choice, LARGEST_REPLY_ID, LARGEST_SAFE_ID, + read_op_globals, parse_id, parse_int_in, parse_iso, parse_moment, parse_idempotency_key, parse_choice, LARGEST_REPLY_ID, LARGEST_SAFE_ID, }; export type {Op_globals}; From c7308907d5c6daf6b731538e6d0f121ace282742 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 16:48:45 -0700 Subject: [PATCH 02/24] feat: a send's refused idempotency key has a code of its own A send route refuses a key two ways: Reply is still making an earlier send with that key, or the key was used for a different send. Both are 409s under the route's own family, contact for the email and directLinkedIn for the LinkedIn sends, and neither sent anything, so a caller needs to tell them from a refusal of the send itself. They are idempotency_key.in_use and idempotency_key.reused, read only under 409 and only in the route's own family; every other answer maps as before. The codes sit in one table with the CLI code each maps to. --- src/__tests__/operations/commands.test.ts | 4 +- src/__tests__/operations/direct-send.test.ts | 42 +++++++++++++++++++- src/operations/commands.ts | 11 +++-- src/operations/direct-send.ts | 38 ++++++++++++++---- 4 files changed, 82 insertions(+), 13 deletions(-) diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index 7902225..56d8791 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -243,9 +243,11 @@ describe('operations/commands', ()=>{ expect(flat, text).toContain('direct-send get reads it later, and direct-send cancel stops one not yet sent'); expect(flat, text).toContain('An answer without state comes from a Reply that does not know --send-after and --schedule-id'); expect(flat, text).toContain('--idempotency-key goes as the Idempotency-Key header'); + expect(flat, text).toContain('A Reply that knows the header answers a repeat with the same key with the send the key first made; while that one is still ' + + 'being made the answer is idempotency_key.in_use, and the same key on a different send is idempotency_key.reused'); // Exactly the codes its endpoint publishes, then the shared ones, as the help lists them. const listed = text.split('\nErrors')[1].split('\nExit codes')[0].split('\n').slice(1).map(l=>l.trim()); - expect(listed, name).toEqual([...codes, 'access.denied', 'access.feature_unavailable', 'rate_limited', 'reply.unavailable', + expect(listed, name).toEqual([...codes, 'idempotency_key.in_use', 'idempotency_key.reused', 'access.denied', 'access.feature_unavailable', 'rate_limited', 'reply.unavailable', 'reply.refused', 'reply.invalid_request', 'outcome.unknown']); } }); diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index 13f8a78..b6b724a 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -702,7 +702,7 @@ describe('a send for later', ()=>{ expect((e as {hint?: string}).hint).toContain('may send it twice'); }); - it('a 404 with no code of Reply own stays reply.refused, status 404 and no reply code, an empty body or a problem without one', async()=>{ + it('a 404 with no code of Reply\'s own stays reply.refused, status 404 and no reply code, an empty body or a problem without one', async()=>{ const bare: [string, ()=>Response][] = [ ['empty', ()=>new Response(null, {status: 404})], ['problem', ()=>json({title: 'Not Found', status: 404}, 404, {'Content-Type': 'application/problem+json'})], @@ -720,3 +720,43 @@ describe('a send for later', ()=>{ } }); }); + +describe('a send made with an idempotency key', ()=>{ + const KEY = {idempotencyKey: 'send-456-step-2'}; + const SENDS: [Direct_send_name, unknown, Direct_send_opts, string][] = [ + ['send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...KEY}, 'contact'], + ['linkedin-connect', {note: NOTE}, {...LINKEDIN_OPTS, ...KEY}, 'directLinkedIn'], + ['linkedin-message', {body: TEXT}, {...LINKEDIN_OPTS, ...KEY}, 'directLinkedIn'], + ['linkedin-inmail', {subject: SUBJECT, body: TEXT}, {...LINKEDIN_OPTS, ...KEY}, 'directLinkedIn'], + ['linkedin-voice', {script: SCRIPT}, {...LINKEDIN_OPTS, ...KEY}, 'directLinkedIn'], + ]; + + it('maps the key Reply holds for a send still being made, and the key reused for another send, each definite', async()=>{ + for (const [name, message, opts, family] of SENDS) + { + for (const [reply_code, code] of [['idempotencyKeyInUse', 'idempotency_key.in_use'], ['idempotencyKeyReused', 'idempotency_key.reused']]) + { + mock_fetch.mockReset(); + answer(json({code: `${family}.${reply_code}`, detail: 'Idempotency-Key conflict.'}, 409)); + const e = await failure(name, message, opts); + expect(e, `${name} ${reply_code}`).toMatchObject({code, exit_code: 1, status: 409, reply_code: `${family}.${reply_code}`, + ids: {contact_id: 456}}); + expect(sent(), name).toHaveLength(1); + } + } + }); + + it('reads those codes only under 409 and only in the send route\'s own family; any other answer is mapped as before', async()=>{ + const cases: [Direct_send_name, unknown, Direct_send_opts, Response][] = [ + ['send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...KEY}, json({code: 'contact.idempotencyKeyInUse'}, 400)], + ['send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...KEY}, json({code: 'directLinkedIn.idempotencyKeyInUse'}, 409)], + ['linkedin-message', {body: TEXT}, {...LINKEDIN_OPTS, ...KEY}, json({code: 'contact.idempotencyKeyReused'}, 409)], + ]; + for (const [name, message, opts, res] of cases) + { + mock_fetch.mockReset(); + answer(res); + expect(await failure(name, message, opts), name).toMatchObject({code: 'reply.refused', exit_code: 1}); + } + }); +}); diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 88fe494..53c1945 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -302,7 +302,12 @@ const LATER = 'With --send-after Reply holds the send until that moment, given w + 'send; state, when Reply gives it, says whether it has gone out: queued or sending is not yet, then sent, failed or\n' + 'cancelled. direct-send get reads it later, and direct-send cancel stops one not yet sent. An\n' + 'answer without state comes from a Reply that does not know --send-after and --schedule-id: it sent at once, as\n' - + 'without them. --idempotency-key goes as the Idempotency-Key header, never in the body.\n'; + + 'without them. --idempotency-key goes as the Idempotency-Key header, never in the body. A Reply that knows the header\n' + + 'answers a repeat with the same key with the send the key first made; while that one is still being made the answer\n' + + 'is idempotency_key.in_use, and the same key on a different send is idempotency_key.reused. Neither sends anything.\n'; + +// The refusals of a send's key, the same on every direct send, after each send's own. +const KEY_CODES = ['idempotency_key.in_use', 'idempotency_key.reused']; // One send's example with the person and the text both on stdin. const piped_send = (command: string, contact: string, message: string, flags: string): string=> @@ -317,7 +322,7 @@ later_options(add_contact_options(contact_command.command('send-email'), true) .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')], - ['contact.not_found', ...IMPORT_CODES, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted'], true, + ['contact.not_found', ...IMPORT_CODES, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted', ...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' @@ -350,7 +355,7 @@ const linkedin_send = ( .option('--linkedin-account-id ', 'The LinkedIn account to send from (see `account list`)') .option('--message ', `Only -: the ${message} as JSON on stdin`)) .description(description) - .addHelpText('after', help(examples, [...LINKEDIN_SEND_CODES, ...codes], true, extra + LATER + SENT_TO('linkedin', what), + .addHelpText('after', help(examples, [...LINKEDIN_SEND_CODES, ...codes, ...KEY_CODES], true, extra + LATER + SENT_TO('linkedin', what), SEND_TWICE(what))) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index 9945893..e06be16 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -145,7 +145,34 @@ const REFUSALS: Record = const LIMITS: Record = {'directLinkedIn.dailyLimitReached': 'daily', 'directLinkedIn.weeklyLimitReached': 'weekly'}; -const send_refusal = (a: Answer, contact_id: number): Operation_error=>{ +type Refusal = {status: number; code: string; title: string; hint?: string}; + +// The codes of a send made for later, each Reply's code with the CLI code it maps to, here and +// nowhere else. A send route answers a refused Idempotency-Key under its own family: contact for the +// email, directLinkedIn for the LinkedIn sends. Neither sent anything. +const KEY_IN_USE = { + status: 409, code: 'idempotency_key.in_use', title: 'Reply is still making an earlier send with this idempotency key, so this one sent nothing.', + hint: 'Run it again with the same key once that send is made: Reply answers a repeat with the send the key first made.', +}; +const KEY_REUSED = { + status: 409, code: 'idempotency_key.reused', title: 'Reply already took this idempotency key for a different send, so nothing was sent.', + hint: 'Give each new send a key of its own.', +}; +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 refusal a table holds for this answer, under the status Reply publishes it with, or undefined. +const known_refusal = (a: Answer, table: Record): Operation_error | undefined=>{ + const reply_code = reply_code_of(a); + const known = reply_code === undefined ? undefined : table[reply_code]; + return known !== undefined && known.status === a.status + ? new Operation_error(known.code, known.title, {status: a.status, reply_code, detail: detail_of(a), hint: known.hint}) + : undefined; +}; + +const send_refusal = (a: Answer, contact_id: number, by: Channel): Operation_error=>{ const reply_code = reply_code_of(a); if (a.status === 404 && (reply_code === 'contact.notFound' || reply_code === 'directLinkedIn.contactNotFound')) { @@ -158,12 +185,7 @@ const send_refusal = (a: Answer, contact_id: number): Operation_error=>{ retry_after: parse_retry_after(a.headers['retry-after']) ?? undefined, details: {limit: LIMITS[reply_code]}, }); } - const known = reply_code === undefined ? undefined : REFUSALS[reply_code]; - if (known !== undefined && known.status === a.status) - { - return new Operation_error(known.code, known.title, {status: a.status, reply_code, detail: detail_of(a)}); - } - return refusal(a, 'write'); + return known_refusal(a, REFUSALS) ?? known_refusal(a, KEY_REFUSALS[by]) ?? refusal(a, 'write'); }; const positive_integer = (v: unknown): number | null=> @@ -298,7 +320,7 @@ const handle_direct_send = async( } if (a.status !== 200) { - throw send_refusal(a, ensured.id); + throw send_refusal(a, ensured.id, by); } print_result(result_of(name, ensured, expect_object(a, 'write')), g); } catch (e) { From d38374f5f28b092fe3725f9c323f8ea230300795 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 16:54:13 -0700 Subject: [PATCH 03/24] feat: direct-send get and direct-send cancel read and stop a send made for later A send made with --send-after answers a reference, and until now nothing could follow it: an agent that scheduled a message could neither see whether it went out nor take it back. direct-send get reads GET /v3/direct-sends/{reference} and direct-send cancel posts to its /cancel route. The reference is Reply's and is passed on encoded into the path, never parsed. A cancel of a send already cancelled is a success, so a cancel whose answer was lost says that running it again is safe. Reply's directSend codes get CLI codes of their own; a bare 404 from a Reply without the route stays reply.refused. --- src/__tests__/operations/commands.test.ts | 26 ++- src/__tests__/operations/direct-sends.test.ts | 170 ++++++++++++++++++ src/__tests__/operations/program.test.ts | 15 ++ src/index.ts | 8 +- src/operations/commands.ts | 33 +++- src/operations/direct-send.ts | 18 +- src/operations/direct-sends.ts | 64 +++++++ 7 files changed, 329 insertions(+), 5 deletions(-) create mode 100644 src/__tests__/operations/direct-sends.test.ts create mode 100644 src/operations/direct-sends.ts diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index 56d8791..573840d 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -1,6 +1,7 @@ import {describe, it, expect} from 'vitest'; import type {Command} from 'commander'; -import {sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command} from '../../operations/commands'; +import {sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command, + direct_send_command} from '../../operations/commands'; const sub = (parent: Command, name: string): Command=>{ const found = parent.commands.find(c=>c.name() === name); @@ -26,6 +27,29 @@ describe('operations/commands', ()=>{ expect(inbox_command.commands.map(c=>c.name())).toEqual(['list', 'get', 'reply', 'categories', 'categorize', 'mark-read', 'mark-unread']); expect(account_command.commands.map(c=>c.name())).toEqual(['list']); expect(schedule_command.commands.map(c=>c.name())).toEqual(['list']); + expect(direct_send_command.commands.map(c=>c.name())).toEqual(['get', 'cancel']); + }); + + it('direct-send get and cancel each take one reference and no flag, and list the refusals Reply gives each', ()=>{ + const expected: [string, string[], boolean][] = [ + ['get', ['direct_send.not_found', 'direct_send.not_owned'], false], + ['cancel', ['direct_send.not_found', 'direct_send.not_owned', 'direct_send.already_sent', 'direct_send.already_failed'], true], + ]; + for (const [name, codes, write] of expected) + { + const c = sub(direct_send_command, name); + expect(flags(c), name).toEqual([]); + expect(c.registeredArguments.map(a=>a.name()), name).toEqual(['reference']); + const text = help_of(c); + const flat = text.replace(/\s+/g, ' '); + expect(text, name).toContain(codes.map(code=>` ${code}\n`).join('')); + expect(text.includes('outcome.unknown'), name).toBe(write); + expect(flat, name).toContain('The reference is Reply\'s, from the answer of a send made with --send-after'); + expect(flat, name).toContain('state is Reply\'s own word: queued or sending is not yet sent, then sent, failed or cancelled'); + expect(flat, name).toContain('A Reply without this route answers reply.refused with status 404 and no reply_code'); + } + expect(help_of(sub(direct_send_command, 'cancel')).replace(/\s+/g, ' ')) + .toContain('Cancelling a send already cancelled answers it again, so running it again is safe'); }); it('schedule list takes no flag and no id, and says how a time zone, a weekday, a time and a state are written', ()=>{ diff --git a/src/__tests__/operations/direct-sends.test.ts b/src/__tests__/operations/direct-sends.test.ts new file mode 100644 index 0000000..20c163a --- /dev/null +++ b/src/__tests__/operations/direct-sends.test.ts @@ -0,0 +1,170 @@ +import {describe, it, expect, beforeEach} from 'vitest'; +import {mock_fetch, json, ctx, sent, answer, capture} from './helpers'; +import {handle_direct_send_get, handle_direct_send_cancel} from '../../operations/direct-sends'; + +beforeEach(()=>{ mock_fetch.mockReset(); }); + +const QUEUED = { + reference: 'email-1001', channel: 'email', contactId: 456, state: 'queued', sendAfter: '2026-11-03T14:00:00Z', + sentAt: null, messageId: null, failureReason: null, cancelledAt: null, +}; +const CANCELLED = {...QUEUED, state: 'cancelled', cancelledAt: '2026-11-02T09:15:00Z'}; + +const get = async(reference: string)=>JSON.parse((await capture(()=>handle_direct_send_get(reference, ctx(), {json: true}))).out); +const cancel = async(reference: string)=>JSON.parse((await capture(()=>handle_direct_send_cancel(reference, ctx(), {json: true}))).out); +const failure = (fn: () => Promise)=>fn().catch((x: unknown)=>x); + +const lost_connection = ()=>Object.assign(new TypeError('fetch failed'), + {cause: Object.assign(new Error('ECONNRESET'), {code: 'ECONNRESET'})}); + +// A 404 with no code of Reply's own: how a Reply without the route answers. +const BARE_404: [string, ()=>Response][] = [ + ['empty', ()=>new Response(null, {status: 404})], + ['problem without a code', ()=>json({title: 'Not Found', status: 404}, 404, {'Content-Type': 'application/problem+json'})], +]; + +describe('direct-send get', ()=>{ + it('reads one send by its reference and answers Reply\'s model under the CLI\'s names', async()=>{ + answer(json(QUEUED)); + expect(await get('email-1001')).toStrictEqual({ + reference: 'email-1001', 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, + }); + expect(sent()).toEqual([{method: 'GET', url: 'https://api/v3/direct-sends/email-1001', body: undefined}]); + }); + + it('gives what Reply leaves out as null, and Reply\'s state as its own word, one the CLI does not know included', async()=>{ + answer(json({reference: 'linkedin-1042', state: 'held', sentAt: '2026-11-03T14:00:02Z', messageId: 'm-1', + failureReason: 'notConnected'})); + expect(await get('linkedin-1042')).toStrictEqual({ + reference: 'linkedin-1042', channel: null, contact_id: null, state: 'held', send_after: null, + sent_at: '2026-11-03T14:00:02Z', message_id: 'm-1', failure_reason: 'notConnected', cancelled_at: null, + }); + }); + + it('sends the reference as given, encoded into the path and never checked or parsed', async()=>{ + for (const [reference, path] of [['ds_8F2k', 'ds_8F2k'], ['a/b c?d', 'a%2Fb%20c%3Fd'], ['email-0', 'email-0']]) + { + mock_fetch.mockReset(); + answer(json({...QUEUED, reference})); + await get(reference); + expect(sent()[0].url, reference).toBe(`https://api/v3/direct-sends/${path}`); + } + }); + + it('refuses a blank reference before any call', async()=>{ + for (const blank of ['', ' ']) + { + expect(await failure(()=>handle_direct_send_get(blank, ctx(), {})), JSON.stringify(blank)) + .toMatchObject({code: 'usage.reference', exit_code: 2}); + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('maps Reply\'s two refusals of a read, each under the status Reply publishes it with', async()=>{ + const cases: [Response, string, string | undefined][] = [ + [json({code: 'directSend.notFound', detail: 'Direct send not found.'}, 404), 'direct_send.not_found', 'directSend.notFound'], + [json({code: 'directSend.notOwned', detail: 'Not yours.'}, 403), 'direct_send.not_owned', 'directSend.notOwned'], + [json({code: 'directSend.notOwned'}, 404), 'reply.refused', 'directSend.notOwned'], + [json({code: 'directSend.forbidden'}, 403), 'access.feature_unavailable', 'directSend.forbidden'], + [json({code: 'directSend.somethingElse'}, 400), 'reply.refused', 'directSend.somethingElse'], + ]; + for (const [res, code, reply_code] of cases) + { + mock_fetch.mockReset(); + answer(res); + const e = await failure(()=>handle_direct_send_get('email-1001', ctx(), {})); + expect(e, code).toMatchObject({code, exit_code: 1}); + expect((e as {reply_code?: string}).reply_code, code).toBe(reply_code); + } + }); + + it('a 404 with no code of Reply\'s own is reply.refused, status 404 and no reply code', async()=>{ + for (const [label, res] of BARE_404) + { + mock_fetch.mockReset(); + answer(res()); + const e = await failure(()=>handle_direct_send_get('email-1001', ctx(), {})); + expect(e, label).toMatchObject({code: 'reply.refused', status: 404, exit_code: 1}); + expect((e as {reply_code?: string}).reply_code, label).toBeUndefined(); + } + }); + + it('an answer without a reference or a state cannot be read, and the read is safe to make again', async()=>{ + for (const body of [{...QUEUED, reference: undefined}, {...QUEUED, state: ''}, [QUEUED], 'ok']) + { + mock_fetch.mockReset(); + answer(json(body)); + expect(await failure(()=>handle_direct_send_get('email-1001', ctx(), {})), JSON.stringify(body)) + .toMatchObject({code: 'reply.unavailable', exit_code: 1}); + } + }); +}); + +describe('direct-send cancel', ()=>{ + it('cancels one send by its reference and answers the send as Reply now holds it', async()=>{ + answer(json(CANCELLED)); + expect(await cancel('email-1001')).toStrictEqual({ + reference: 'email-1001', channel: 'email', contact_id: 456, state: 'cancelled', send_after: '2026-11-03T14:00:00Z', + sent_at: null, message_id: null, failure_reason: null, cancelled_at: '2026-11-02T09:15:00Z', + }); + expect(sent()).toEqual([{method: 'POST', url: 'https://api/v3/direct-sends/email-1001/cancel', body: undefined}]); + }); + + it('a cancel of a send already cancelled is a success again, as Reply answers it', async()=>{ + answer(json(CANCELLED), json(CANCELLED)); + expect(await cancel('email-1001')).toMatchObject({state: 'cancelled'}); + expect(await cancel('email-1001')).toMatchObject({state: 'cancelled'}); + expect(mock_fetch).toHaveBeenCalledTimes(2); + }); + + it('maps Reply\'s four refusals of a cancel, each definite', async()=>{ + const cases: [Response, string][] = [ + [json({code: 'directSend.notFound'}, 404), 'direct_send.not_found'], + [json({code: 'directSend.notOwned'}, 403), 'direct_send.not_owned'], + [json({code: 'directSend.alreadySent'}, 409), 'direct_send.already_sent'], + [json({code: 'directSend.alreadyFailed'}, 409), 'direct_send.already_failed'], + [json({code: 'directSend.alreadySent'}, 400), 'reply.refused'], + ]; + for (const [res, code] of cases) + { + mock_fetch.mockReset(); + answer(res); + expect(await failure(()=>handle_direct_send_cancel('email-1001', ctx(), {})), code).toMatchObject({code, exit_code: 1}); + expect(mock_fetch, code).toHaveBeenCalledTimes(1); + } + }); + + it('a 404 with no code of Reply\'s own is reply.refused, status 404 and no reply code', async()=>{ + for (const [label, res] of BARE_404) + { + mock_fetch.mockReset(); + answer(res()); + const e = await failure(()=>handle_direct_send_cancel('email-1001', ctx(), {})); + expect(e, label).toMatchObject({code: 'reply.refused', status: 404, exit_code: 1}); + expect((e as {reply_code?: string}).reply_code, label).toBeUndefined(); + } + }); + + it('an answer that may hide a cancel is outcome.unknown (exit 3), made once, and says running it again is safe', async()=>{ + const answers: [string, ()=>void][] = [ + ['lost answer', ()=>{ mock_fetch.mockRejectedValueOnce(lost_connection()); }], + ['503', ()=>answer(json({title: 'Service Unavailable'}, 503))], + ['unreadable 200', ()=>answer(json('ok', 200))], + ]; + for (const [label, give] of answers) + { + mock_fetch.mockReset(); + give(); + const e = await failure(()=>handle_direct_send_cancel('email-1001', ctx(), {})); + expect(e, label).toMatchObject({code: 'outcome.unknown', exit_code: 3}); + expect((e as {hint?: string}).hint ?? '', label).toContain('running it again is safe'); + expect(mock_fetch, label).toHaveBeenCalledTimes(1); + } + }); + + it('refuses a blank reference before any call', async()=>{ + expect(await failure(()=>handle_direct_send_cancel(' ', ctx(), {}))).toMatchObject({code: 'usage.reference', exit_code: 2}); + expect(mock_fetch).not.toHaveBeenCalled(); + }); +}); diff --git a/src/__tests__/operations/program.test.ts b/src/__tests__/operations/program.test.ts index de5e5c3..64e6990 100644 --- a/src/__tests__/operations/program.test.ts +++ b/src/__tests__/operations/program.test.ts @@ -210,6 +210,21 @@ describe('the program', ()=>{ expect((mock_fetch.mock.calls[0] as [string, RequestInit])[0]).toBe('https://api.reply.io/v3/schedules'); }); + it('direct-send is a work command of its own: no reference exits 2, a refused cancel exits 1 with its code', async()=>{ + for (const verb of ['get', 'cancel']) + { + const {code} = await run_program(['--json', '-q', '-k', 'key-1', 'direct-send', verb]); + expect(code, verb).toBe(2); + } + expect(mock_fetch).not.toHaveBeenCalled(); + answer(json({code: 'directSend.alreadySent', detail: 'Already sent.'}, 409, {'Content-Type': 'application/problem+json'})); + const {code, err} = await run_program(['--json', '-q', '-k', 'key-1', 'direct-send', 'cancel', 'email-1001']); + expect(code).toBe(1); + expect(JSON.parse(err)).toMatchObject({error: {code: 'direct_send.already_sent', status: 409}}); + const [url, init] = mock_fetch.mock.calls[0] as [string, RequestInit]; + expect([init.method, url]).toEqual(['POST', 'https://api.reply.io/v3/direct-sends/email-1001/cancel']); + }); + it('a usage error exits 2 before any request', async()=>{ const {code, err} = await run_program(['--json', '-k', 'key-1', 'sequence', 'stats', '123', '--from', '2026-10-02', '--to', '2026-10-01']); expect(code).toBe(2); diff --git a/src/index.ts b/src/index.ts index a874344..6598ea0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,7 +7,9 @@ import {team_command} from './commands/team'; import {api_command} from './commands/api'; import {skills_command} from './commands/skills'; import {install_command} from './commands/install'; -import {sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command} from './operations/commands'; +import { + sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command, direct_send_command, +} from './operations/commands'; import {update_notice} from './selfupdate/notice'; import {CliError, format_hint} from './utils/errors'; import {info, set_quiet} from './utils/output'; @@ -46,7 +48,9 @@ const build_program = (): Command=>{ const WORK = 'Work with your Reply account:'; const SETUP = 'Setup:'; - for (const c of [sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command, api_command]) + for (const c of [ + sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command, direct_send_command, api_command, + ]) { program.addCommand(c.helpGroup(WORK)); } diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 53c1945..e6d06e8 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -17,6 +17,7 @@ import {handle_contact_find, handle_contact_get, handle_contact_update, handle_c import {handle_direct_send, type Direct_send_name} from './direct-send'; import {handle_account_list} from './accounts'; import {handle_schedule_list} from './schedules'; +import {handle_direct_send_get, handle_direct_send_cancel} from './direct-sends'; const P = PROGRAM_NAME; const COMMON_ERRORS = [ @@ -539,4 +540,34 @@ schedule_command.command('list') await handle_schedule_list(ctx, g); })); -export {sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command}; +const direct_send_command = new Command('direct-send').description('Read or cancel a direct send Reply holds to send later'); + +const DIRECT_SEND = 'Result: {"reference","channel","contact_id","state","send_after","sent_at","message_id","failure_reason",\n' + + '"cancelled_at"}, Reply\'s fields under these names, each null when Reply gives none. The reference is Reply\'s, from the\n' + + 'answer of a send made with --send-after; it is passed on as given and never read. state is Reply\'s own word: queued\n' + + 'or sending is not yet sent, then sent, failed or cancelled. A Reply without this route answers reply.refused with\n' + + 'status 404 and no reply_code; direct_send.not_found is a reference that Reply has no send for.\n'; + +direct_send_command.command('get') + .argument('', 'The send\'s reference, as a send made with --send-after answered it') + .description('One direct send as Reply holds it: whether it has gone out, when, and why it failed') + .addHelpText('after', help([ex('direct-send get email-1001')], ['direct_send.not_found', 'direct_send.not_owned'], false, DIRECT_SEND)) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_direct_send_get(cmd.args[0], ctx, g); + })); + +direct_send_command.command('cancel') + .argument('', 'The send\'s reference, as a send made with --send-after answered it') + .description('Stop a direct send that has not gone out yet') + .addHelpText('after', help([ex('direct-send cancel email-1001')], + ['direct_send.not_found', 'direct_send.not_owned', 'direct_send.already_sent', 'direct_send.already_failed'], true, + DIRECT_SEND + 'The answer is the send as Reply now holds it, state cancelled. Cancelling a send already cancelled answers\n' + + 'it again, so running it again is safe. direct_send.already_sent and direct_send.already_failed mean the send\n' + + 'was past cancelling; nothing changed.\n')) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_direct_send_cancel(cmd.args[0], ctx, g); + })); + +export {sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command, direct_send_command}; diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index e06be16..c52e3de 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -162,6 +162,22 @@ 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 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 = { + 'directSend.notFound': { + status: 404, code: 'direct_send.not_found', title: 'Reply has no direct send under that reference that this account can see.', + }, + 'directSend.notOwned': { + status: 403, code: 'direct_send.not_owned', title: 'The direct send is not one this user may act on.', + }, + 'directSend.alreadySent': { + status: 409, code: 'direct_send.already_sent', title: 'The direct send has already gone out, so it was not cancelled.', + }, + 'directSend.alreadyFailed': { + status: 409, code: 'direct_send.already_failed', title: 'The direct send has already failed, so it was not cancelled.', + }, +}; // The refusal a table holds for this answer, under the status Reply publishes it with, or undefined. const known_refusal = (a: Answer, table: Record): Operation_error | undefined=>{ @@ -337,5 +353,5 @@ const handle_direct_send = async( } }; -export {handle_direct_send}; +export {handle_direct_send, known_refusal, DIRECT_SEND_REFUSALS}; export type {Direct_send_name, Direct_send_opts}; diff --git a/src/operations/direct-sends.ts b/src/operations/direct-sends.ts new file mode 100644 index 0000000..eff6422 --- /dev/null +++ b/src/operations/direct-sends.ts @@ -0,0 +1,64 @@ +import {Unknown_outcome_error, UsageError} from '../utils/errors'; +import {call_reply, expect_object, refusal, unreadable, open_session, type Answer} from './call'; +import {known_refusal, DIRECT_SEND_REFUSALS} from './direct-send'; +import {print_result} from './result'; +import type {Op_globals} from './options'; +import type {Cli_context} from '../context'; + +// The reference is Reply's and opaque: it is sent as given, encoded into the path, and never read. +const path_of = (reference: string): string=>{ + if (reference.trim() === '') + { + throw new UsageError('No reference was given.', {code: 'usage.reference', hint: 'A send made with --send-after answers its reference.'}); + } + return `/v3/direct-sends/${encodeURIComponent(reference)}`; +}; + +// A send as Reply holds it, under the CLI's names; a field 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. +const direct_send_of = (a: Answer, kind: 'read' | 'write'): Record=>{ + const body = expect_object(a, kind); + if (typeof body.reference !== 'string' || body.reference === '' || typeof body.state !== 'string' || body.state === '') + { + throw unreadable(a, kind); + } + const field = (name: string): unknown=>body[name] ?? null; + return { + reference: body.reference, channel: field('channel'), contact_id: field('contactId'), state: body.state, + send_after: field('sendAfter'), sent_at: field('sentAt'), message_id: field('messageId'), + failure_reason: field('failureReason'), cancelled_at: field('cancelledAt'), + }; +}; + +const handle_direct_send_get = async(reference: string, ctx: Cli_context, g: Op_globals): Promise=>{ + const path = path_of(reference); + const s = await open_session(ctx, g); + const a = await call_reply(s, 'GET', path, 'read'); + if (a.status !== 200) + { + throw known_refusal(a, DIRECT_SEND_REFUSALS) ?? refusal(a, 'read'); + } + print_result(direct_send_of(a, 'read'), g); +}; + +const handle_direct_send_cancel = async(reference: string, ctx: Cli_context, g: Op_globals): Promise=>{ + const path = `${path_of(reference)}/cancel`; + const s = await open_session(ctx, g); + try { + const a = await call_reply(s, 'POST', path, 'write'); + if (a.status !== 200) + { + throw known_refusal(a, DIRECT_SEND_REFUSALS) ?? refusal(a, 'write'); + } + print_result(direct_send_of(a, 'write'), g); + } catch (e) { + // A cancel is safe to repeat: Reply answers a send already cancelled as cancelled again. + if (e instanceof Unknown_outcome_error) + { + e.hint = 'The send may or may not have been cancelled; running it again is safe, and direct-send get reads where it stands.'; + } + throw e; + } +}; + +export {handle_direct_send_get, handle_direct_send_cancel}; From 88e90a40c38f1f5ce8b842f4bea62f1799be1a92 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 16:57:20 -0700 Subject: [PATCH 04/24] feat: inbox events reads the inbox feed forward by cursor Following the inbox meant re-listing it and diffing threads. inbox events reads GET /v3/inbox/events one page at a time: --cursor goes on from the cursor a previous page answered, --since starts at a moment given with its offset and sent in UTC, and with neither Reply reads the last 30 days. The page is {items, has_more, cursor} with the items as Reply gives them, and an empty page keeps its cursor. Reply answers a cursor it will not read as a validation problem that points at /cursor, so that answer is inbox.cursor_refused, whose hint says to start again with --since. --- src/__tests__/operations/commands.test.ts | 18 ++- src/__tests__/operations/inbox-events.test.ts | 112 ++++++++++++++++++ src/__tests__/operations/program.test.ts | 12 ++ src/operations/commands.ts | 22 +++- src/operations/inbox.ts | 58 ++++++++- 5 files changed, 216 insertions(+), 6 deletions(-) create mode 100644 src/__tests__/operations/inbox-events.test.ts diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index 573840d..1ecc8d1 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -24,7 +24,7 @@ describe('operations/commands', ()=>{ expect(contact_list_command.commands.map(c=>c.name())).toEqual(['add-contact']); expect(contact_command.commands.map(c=>c.name())).toEqual(['find', 'get', 'update', 'delete', 'opt-out', 'send-email', 'linkedin-connect', 'linkedin-message', 'linkedin-inmail', 'linkedin-voice']); - expect(inbox_command.commands.map(c=>c.name())).toEqual(['list', 'get', 'reply', 'categories', 'categorize', 'mark-read', 'mark-unread']); + expect(inbox_command.commands.map(c=>c.name())).toEqual(['list', 'events', 'get', 'reply', 'categories', 'categorize', 'mark-read', 'mark-unread']); expect(account_command.commands.map(c=>c.name())).toEqual(['list']); expect(schedule_command.commands.map(c=>c.name())).toEqual(['list']); expect(direct_send_command.commands.map(c=>c.name())).toEqual(['get', 'cancel']); @@ -164,6 +164,22 @@ describe('operations/commands', ()=>{ expect(flags(sub(contact_command, 'delete'))).toEqual([]); }); + it('inbox events takes --cursor, --since and --top, and says how the feed is read forward', ()=>{ + const c = sub(inbox_command, 'events'); + expect(flags(c)).toEqual(['--cursor', '--since', '--top']); + expect(c.registeredArguments).toEqual([]); + const text = help_of(c); + const flat = text.replace(/\s+/g, ' '); + expect(flat, text).toContain('Result: {"items","has_more","cursor"}'); + expect(flat, text).toContain('the items as Reply gives them'); + expect(flat, text).toContain('Give --cursor or --since, not both; with neither, Reply reads the last 30 days'); + expect(flat, text).toContain('loop on has_more, not on the number of items'); + expect(flat, text).toContain('an empty page still carries a cursor'); + expect(flat, text).toContain('inbox.cursor_refused'); + expect(text, text).toContain(' inbox.cursor_refused\n'); + expect(text, text).not.toContain('outcome.unknown'); + }); + it('sequence list and create take the name only through --name -, and create says a repeat may make a second one', ()=>{ expect(flags(sub(sequence_command, 'list'))).toEqual(['--name']); const create = sub(sequence_command, 'create'); diff --git a/src/__tests__/operations/inbox-events.test.ts b/src/__tests__/operations/inbox-events.test.ts new file mode 100644 index 0000000..ebbd3ef --- /dev/null +++ b/src/__tests__/operations/inbox-events.test.ts @@ -0,0 +1,112 @@ +import {describe, it, expect, beforeEach} from 'vitest'; +import {mock_fetch, json, ctx, sent, answer, capture} from './helpers'; +import {handle_inbox_events} from '../../operations/inbox'; + +beforeEach(()=>{ mock_fetch.mockReset(); }); + +const EVENT = { + threadId: 9876, contactId: 456, channel: 'email', lastActivityDate: '2026-11-03T14:02:11Z', sequenceId: 12, + category: 'interested', hasMeetingIntent: false, newFieldReplyAdds: 'kept', + flags: {hasReply: true, hasBounce: false, hasAutoReply: false, hasOutOfOffice: false}, + lastMessage: {messageId: '', isOutbound: false, date: '2026-11-03T14:02:11Z'}, +}; + +type Opts = {cursor?: string; since?: string; top?: string}; +const events = async(opts: Opts = {})=>JSON.parse((await capture(()=>handle_inbox_events(opts, ctx(), {json: true}))).out); +const failure = (opts: Opts)=>handle_inbox_events(opts, ctx(), {}).catch((x: unknown)=>x); + +// How #477 publishes a cursor Reply will not read: a validation problem with no code, pointing at /cursor. +const CURSOR_TOO_OLD = { + title: 'Validation failed', status: 400, detail: 'The request body contains validation errors.', + errors: [{pointer: '/cursor', detail: '\'cursor\' is older than 30 days. Start again with \'since\' (at most 30 days ago) or with no parameters, which reads the last 30 days.'}], +}; +const problem = (body: unknown, status: number)=>json(body, status, {'Content-Type': 'application/problem+json'}); + +describe('inbox events', ()=>{ + it('reads one page of the feed and passes the items on as Reply gives them, under has_more and cursor', async()=>{ + answer(json({items: [EVENT], hasMore: true, cursor: 'AQjfObhYHZgAAADjVg'})); + expect(await events()).toStrictEqual({items: [EVENT], has_more: true, cursor: 'AQjfObhYHZgAAADjVg'}); + expect(sent()).toEqual([{method: 'GET', url: 'https://api/v3/inbox/events', body: undefined}]); + }); + + it('an empty page keeps the cursor Reply gives with it, so the next read goes on from there', async()=>{ + answer(json({items: [], hasMore: false, cursor: 'AQjfObkJcH4Af____w'})); + expect(await events({cursor: 'AQjfObhYHZgAAADjVg'})).toStrictEqual({items: [], has_more: false, cursor: 'AQjfObkJcH4Af____w'}); + }); + + it('sends the cursor as given and encoded, --since in UTC and not shifted, and --top only when given', async()=>{ + const cases: [Opts, string][] = [ + [{cursor: 'AQjf+b/Y=='}, 'cursor=AQjf%2Bb%2FY%3D%3D'], + [{since: '2026-11-03T16:00:00+02:00'}, 'since=2026-11-03T14%3A00%3A00.000Z'], + [{since: '2026-11-03T14:00:00Z', top: '1000'}, 'since=2026-11-03T14%3A00%3A00.000Z&top=1000'], + [{top: '1'}, 'top=1'], + ]; + for (const [opts, query] of cases) + { + mock_fetch.mockReset(); + answer(json({items: [], hasMore: false, cursor: 'c'})); + await events(opts); + expect(sent()[0].url, query).toBe(`https://api/v3/inbox/events?${query}`); + } + }); + + it('refuses --cursor with --since, a blank cursor, a moment without its offset and a --top out of range, before any call', async()=>{ + const cases: [Opts, string][] = [ + [{cursor: 'AQjfObhYHZgAAADjVg', since: '2026-11-03T14:00:00Z'}, 'usage.inbox'], + [{cursor: ' '}, 'usage.inbox'], + [{since: '2026-11-03T14:00:00'}, 'usage.date'], + [{since: '2026-11-03'}, 'usage.date'], + [{top: '0'}, 'usage.range'], + [{top: '1001'}, 'usage.range'], + ]; + for (const [opts, code] of cases) + { + expect(await failure(opts), JSON.stringify(opts)).toMatchObject({code, exit_code: 2}); + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('a cursor Reply will not read is inbox.cursor_refused, which says to start again with --since', async()=>{ + answer(problem(CURSOR_TOO_OLD, 400)); + const e = await failure({cursor: 'AQjfObhYHZgAAADjVg'}); + expect(e).toMatchObject({code: 'inbox.cursor_refused', status: 400, exit_code: 1, details: {fields: ['cursor']}}); + expect((e as {reply_code?: string}).reply_code).toBeUndefined(); + expect((e as {hint?: string}).hint).toContain('--since'); + }); + + it('any other refusal maps as everywhere else', async()=>{ + const cases: [Opts, Response, string][] = [ + // The same pointer when no cursor was sent is not about one the caller holds. + [{since: '2026-11-03T14:00:00Z'}, problem(CURSOR_TOO_OLD, 400), 'reply.invalid_request'], + [{since: '2026-09-01T00:00:00Z'}, problem({title: 'Validation failed', status: 400, errors: [{pointer: '/since', detail: 'too old'}]}, 400), + 'reply.invalid_request'], + [{cursor: 'c'}, problem({code: 'inboxThread.invalidPagination', status: 400}, 400), 'reply.refused'], + [{}, problem({code: 'inboxThread.forbidden', status: 403}, 403), 'access.feature_unavailable'], + [{}, new Response(null, {status: 404}), 'reply.refused'], + [{}, problem({title: 'Not Found', status: 404}, 404), 'reply.refused'], + ]; + for (const [opts, res, code] of cases) + { + mock_fetch.mockReset(); + answer(res); + expect(await failure(opts), `${JSON.stringify(opts)} ${code}`).toMatchObject({code, exit_code: 1}); + } + }); + + it('a 404 with no code of Reply\'s own, from a Reply without the feed, is reply.refused with status 404 and no reply code', async()=>{ + answer(new Response(null, {status: 404})); + const e = await failure({}); + expect(e).toMatchObject({code: 'reply.refused', status: 404}); + expect((e as {reply_code?: string}).reply_code).toBeUndefined(); + }); + + it('a page without its items, has_more or cursor cannot be read, and the read is safe to make again', async()=>{ + for (const body of [{items: [], hasMore: false}, {items: [], cursor: 'c'}, {items: {}, hasMore: false, cursor: 'c'}, + {items: [], hasMore: 'no', cursor: 'c'}, {items: [], hasMore: false, cursor: 7}, [EVENT]]) + { + mock_fetch.mockReset(); + answer(json(body)); + expect(await failure({}), JSON.stringify(body)).toMatchObject({code: 'reply.unavailable', exit_code: 1}); + } + }); +}); diff --git a/src/__tests__/operations/program.test.ts b/src/__tests__/operations/program.test.ts index 64e6990..292463a 100644 --- a/src/__tests__/operations/program.test.ts +++ b/src/__tests__/operations/program.test.ts @@ -225,6 +225,18 @@ describe('the program', ()=>{ expect([init.method, url]).toEqual(['POST', 'https://api.reply.io/v3/direct-sends/email-1001/cancel']); }); + it('inbox events reads its flags through commander: both --cursor and --since exit 2, a refused cursor exits 1 with its code', async()=>{ + const both = await run_program(['--json', '-q', '-k', 'key-1', 'inbox', 'events', '--cursor', 'c1', '--since', '2026-11-03T14:00:00Z']); + expect(both.code).toBe(2); + expect(mock_fetch).not.toHaveBeenCalled(); + answer(json({title: 'Validation failed', status: 400, errors: [{pointer: '/cursor', detail: 'older than 30 days'}]}, 400, + {'Content-Type': 'application/problem+json'})); + const {code, err} = await run_program(['--json', '-q', '-k', 'key-1', 'inbox', 'events', '--cursor', 'c1', '--top', '50']); + expect(code).toBe(1); + expect(JSON.parse(err)).toMatchObject({error: {code: 'inbox.cursor_refused', status: 400}}); + expect((mock_fetch.mock.calls[0] as [string, RequestInit])[0]).toBe('https://api.reply.io/v3/inbox/events?cursor=c1&top=50'); + }); + it('a usage error exits 2 before any request', async()=>{ const {code, err} = await run_program(['--json', '-k', 'key-1', 'sequence', 'stats', '123', '--from', '2026-10-02', '--to', '2026-10-01']); expect(code).toBe(2); diff --git a/src/operations/commands.ts b/src/operations/commands.ts index e6d06e8..7200302 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -8,7 +8,7 @@ import {handle_sequence_list, handle_sequence_create} from './sequence-by-name'; import {handle_sequence_add_contact, handle_sequence_remove_contact} from './sequence-membership'; import {handle_sequence_pause, handle_sequence_start} from './sequence-state'; import { - handle_inbox_list, handle_inbox_get, handle_inbox_categories, handle_inbox_categorize, handle_inbox_mark_read, handle_inbox_mark_unread, + handle_inbox_list, handle_inbox_events, handle_inbox_get, handle_inbox_categories, handle_inbox_categorize, handle_inbox_mark_read, handle_inbox_mark_unread, } from './inbox'; import {handle_inbox_reply} from './inbox-reply'; import {handle_contact_list_add_contact} from './contact-list'; @@ -427,6 +427,26 @@ inbox_command.command('list') await handle_inbox_list(cmd.opts(), ctx, g); })); +inbox_command.command('events') + .option('--cursor ', 'Go on from the cursor a previous page answered, passed back unchanged') + .option('--since ', 'Start at this moment, inclusive, given with its offset; at most 30 days ago') + .option('--top ', 'Items per page, 1-1000 (default: Reply\'s)') + .description('One page of the inbox feed: each thread whose latest message changed, oldest first, read forward by cursor') + .addHelpText('after', help([ex('inbox events --since 2026-11-01T00:00:00Z'), ex('inbox events --cursor AQjfObhYHZgAAADjVg --top 200')], + ['inbox.cursor_refused'], false, + 'Result: {"items","has_more","cursor"}, the items as Reply gives them, one per thread whose latest message, inbound\n' + + 'or outbound, changed: threadId, contactId, channel, lastActivityDate, flags (hasReply, hasBounce, hasAutoReply,\n' + + 'hasOutOfOffice) and lastMessage among them. Give --cursor or --since, not both; with neither, Reply reads the last\n' + + '30 days. Call again with the answered cursor while has_more is true, and loop on has_more, not on the number of\n' + + 'items: an empty page still carries a cursor, and when has_more is false that cursor is where the next read starts.\n' + + '--since goes to Reply in UTC; a moment without its offset is refused (usage.date). A cursor Reply will not read,\n' + + 'one unreadable, older than 30 days or ahead of its clock, is inbox.cursor_refused: start again with --since.\n' + + 'A Reply without the feed answers reply.refused with status 404 and no reply_code.\n')) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_inbox_events(cmd.opts(), ctx, g); + })); + inbox_command.command('get') .argument('', 'Inbox thread id') .option('--limit ', 'Messages per page, 1-20 (default 20)') diff --git a/src/operations/inbox.ts b/src/operations/inbox.ts index c6392c3..ffac791 100644 --- a/src/operations/inbox.ts +++ b/src/operations/inbox.ts @@ -1,9 +1,9 @@ import {Operation_error, UsageError} from '../utils/errors'; import { - call_reply, expect_object, read_page, refusal, reply_code_of, is_object, item_failure, unreadable, open_session, - type Answer, type Op_session, + call_reply, expect_object, read_page, refusal, reply_code_of, detail_of, invalid_fields, is_object, item_failure, unreadable, + open_session, type Answer, type Op_session, } from './call'; -import {parse_id, parse_int_in, parse_iso, parse_choice, type Op_globals} from './options'; +import {parse_id, parse_int_in, parse_iso, parse_moment, parse_choice, type Op_globals} from './options'; import {print_result, with_ids} from './result'; import type {Cli_context} from '../context'; @@ -66,6 +66,56 @@ const handle_inbox_list = async(opts: Inbox_list_opts, ctx: Cli_context, g: Op_g print_result({items: page.items, has_more: page.has_more}, g); }; +type Inbox_events_opts = {cursor?: string; since?: string; top?: string}; + +// Reply refuses a cursor it will not read (unreadable, older than 30 days, or ahead of its clock) +// as a validation problem with no code that points at /cursor; the three differ only in their text. +const cursor_refused = (a: Answer, fields: string[]): Operation_error=> + new Operation_error('inbox.cursor_refused', 'Reply would not read the cursor: unreadable, older than 30 days or ahead of its clock.', { + status: a.status, detail: detail_of(a), details: {fields}, + hint: 'Start again with --since (at most 30 days ago), or with neither flag to read the last 30 days.', + }); + +const handle_inbox_events = async(opts: Inbox_events_opts, ctx: Cli_context, g: Op_globals): Promise=>{ + if (opts.cursor !== undefined && opts.since !== undefined) + { + throw new UsageError('Give --cursor or --since, not both.', {code: 'usage.inbox'}); + } + const query = new URLSearchParams(); + if (opts.cursor !== undefined) + { + // Reply's cursor is opaque: it goes back as given, never read. + if (opts.cursor.trim() === '') + { + throw new UsageError('--cursor is empty.', {code: 'usage.inbox', hint: 'Pass the cursor a previous page answered, unchanged.'}); + } + query.set('cursor', opts.cursor); + } + if (opts.since !== undefined) + { + // Reply's since is inclusive already, so the moment goes as given, in UTC. + query.set('since', parse_moment(opts.since, '--since')); + } + if (opts.top !== undefined) + { + query.set('top', String(parse_int_in(opts.top, '--top', 1, 1000, 0))); + } + const s = await open_session(ctx, g); + const q = query.toString(); + const a = await call_reply(s, 'GET', q === '' ? '/v3/inbox/events' : `/v3/inbox/events?${q}`, 'read'); + if (a.status !== 200) + { + const fields = opts.cursor !== undefined && a.status === 400 && reply_code_of(a) === undefined ? invalid_fields(a) : undefined; + throw fields?.includes('cursor') ? cursor_refused(a, fields) : refusal(a, 'read'); + } + const body = expect_object(a, 'read'); + if (!Array.isArray(body.items) || typeof body.hasMore !== 'boolean' || typeof body.cursor !== 'string') + { + throw unreadable(a, 'read'); + } + print_result({items: body.items, has_more: body.hasMore, cursor: body.cursor}, g); +}; + // INTERIM (API gap): GET /v3/inbox/threads/{id} carries the thread's whole history inline, every // body included and with no limit, and the thread has no subject of its own. // Needed: a thread without its history inline, and a subject field. @@ -216,7 +266,7 @@ const handle_inbox_mark_unread = (thread_arg: string, ctx: Cli_context, g: Op_gl mark_thread(thread_arg, false, ctx, g); export { - handle_inbox_list, handle_inbox_get, handle_inbox_categories, handle_inbox_categorize, + handle_inbox_list, handle_inbox_events, handle_inbox_get, handle_inbox_categories, handle_inbox_categorize, handle_inbox_mark_read, handle_inbox_mark_unread, thread_not_found, SOURCES, CHANNELS, }; export type {Channel}; From 7538bc61c57a540ab0145444a947c8e3eecd696b Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 16:58:55 -0700 Subject: [PATCH 05/24] docs: the README describes a send for later, direct-send and the inbox feed The command table gains the three send flags, direct-send get and cancel, and inbox events. A section says what status "sent" and state each mean, so a caller does not read a queued send as one that has gone out, how the idempotency key is sent and refused, and how the feed is read forward by cursor. The note on re-running after exit 3 now says a key does not make a send safe to repeat, since a Reply that does not know the header would send again. --- README.md | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0f5bac3..c13f6b4 100644 --- a/README.md +++ b/README.md @@ -198,10 +198,14 @@ prints JSON (indented; compact with `--json`) and says what happened in a stable | `reply contact update ( \| ) --fields -` | change some fields and custom fields; null clears one → `updated` | | `reply contact delete ` | → `deleted` | | `reply contact opt-out ` | → `opted_out` | -| `reply contact send-email --email-account-id N --message -` | one email now, outside any sequence → `sent` | +| `reply contact send-email --email-account-id N --message -` | one email outside any sequence → `sent` | | `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` | +| `reply direct-send get ` | a send as Reply holds it: whether it has gone out, when, and why it failed | +| `reply direct-send cancel ` | stop a send that has not gone out yet → `state` `cancelled` | | `reply inbox list (--contact-id \| --sequence-id) [--source] [--channel] [--category-id] [--since]` | one page of threads | +| `reply inbox events [--cursor … \| --since …] [--top N]` | one page of the inbox feed, read forward by cursor | | `reply inbox get ` | a thread with its subject, and one page of its messages | | `reply inbox reply --message -` | reply in the thread, on its own channel → `sent` | | `reply inbox categories` | the categories a thread can be filed under | @@ -304,6 +308,51 @@ lengths Reply publishes (a LinkedIn message's 8000 characters, an InMail's 200 a 1000) are refused before anything is sent. Reply reads `{{…}}` in a LinkedIn text as its template variables, and refuses one it cannot fill with `linkedin.missing_variables`. +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 offset is refused +(`usage.date`). `--schedule-id` names the sending schedule Reply times the send by (see `reply +schedule list`). The answer then adds Reply's `reference`, `send_after` and `state`, each only when +Reply gives it. `status: "sent"` means Reply took the send, and `state`, when present, says whether +it has gone out: `queued` or `sending` is not yet, then `sent`, `failed` or `cancelled`. `reply +direct-send get ` reads the send later, and `reply direct-send cancel ` stops +one that has not gone out; the reference is Reply's, passed on as given. An answer without `state` +comes from a Reply that does not know these flags yet: it sent at once, as without them. + +`--idempotency-key` goes to Reply as the `Idempotency-Key` header, never in the body. A Reply that +knows the header answers a repeat with the same key with the send the key first made; while that +one is still being made the answer is `idempotency_key.in_use`, and the same key on a different +send is `idempotency_key.reused`. Neither sends anything. + +```sh +echo '{"body":"Following up on my note."}' | reply contact linkedin-message --contact-id 456 --linkedin-account-id 34 --message - --send-after 2026-11-03T14:00:00Z --idempotency-key follow-up-456-1 +# {"status":"sent",…,"reference":"linkedin-1042","send_after":"2026-11-03T14:00:00Z","state":"queued"} +reply direct-send get linkedin-1042 +reply direct-send cancel linkedin-1042 +``` + +`direct-send cancel` of a send already cancelled answers it again. A send already gone out or +failed is `direct_send.already_sent` or `direct_send.already_failed`, and a reference Reply has no +send for is `direct_send.not_found`. + +`reply inbox events` reads the inbox feed forward. Each page holds the threads whose latest message, +inbound or outbound, changed, oldest first and as Reply gives them, with `has_more` and a `cursor`. +Start with `--since ` (inclusive, at most 30 days ago) or with neither flag, which reads the +last 30 days, then pass the answered cursor back with `--cursor` while `has_more` is true. Loop on +`has_more`, not on the number of items: an empty page still carries a cursor, and when `has_more` is +false that cursor is where the next read starts. A cursor Reply will not read, one unreadable, older +than 30 days or ahead of its clock, is `inbox.cursor_refused`: start again with `--since`. + +```sh +reply inbox events --since 2026-11-01T00:00:00Z --json +# {"items":[{"threadId":9876,"contactId":456,"channel":"email","lastActivityDate":"2026-11-03T14:02:11Z",…}], +# "has_more":true,"cursor":"AQjfObhYHZgAAADjVg"} +reply inbox events --cursor AQjfObhYHZgAAADjVg --json +``` + +A Reply that does not have `direct-send get`, `direct-send cancel` or the feed yet answers +`reply.refused` with status 404 and no `reply_code`. + `reply schedule list` gives every sending schedule the account can use, in one answer and in the order Reply gives them: its `time_zone_id` as Reply holds it, a Windows time zone identifier such as `Eastern Standard Time`, whether it reads its windows in each recipient's own time zone, whether it @@ -326,7 +375,8 @@ reply schedule list --json re-run. On exit 3 (outcome unknown) a reply or a send may already have gone, and running it again may send it twice, unless the hint says nothing was sent: a send whose contact's import lost its answer was never made, and its hint says so; run again, it answers `contact.already_held` if that import did -create the contact. +create the contact. An `--idempotency-key` does not change this: a Reply that does not know the +header yet would make the send again. For `inbox reply`, read the thread with `reply inbox get` before trying again. For `sequence create`, Reply allows two sequences of one name, so after exit 3 look the name up with `sequence list --name -` first. Every other work command can simply be run again; a `contact delete` From bdfabf0d352208cb2c22b910313f571861163383 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 16:59:35 -0700 Subject: [PATCH 06/24] refactor: call_reply says its own headers are added to the ones every call carries The comment named the headers by the object that holds them; it now says what they are. --- src/operations/call.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/operations/call.ts b/src/operations/call.ts index 46c0a87..4504abd 100644 --- a/src/operations/call.ts +++ b/src/operations/call.ts @@ -38,7 +38,7 @@ const detail_of = (a: Answer): string | undefined=>{ // One call to Reply for an operation. Every HTTP status comes back as an Answer for the command // to read. If Reply can't be reached, nothing happened, so that becomes reply.unavailable. A // write whose answer was lost passes through as outcome.unknown. Headers given here are this call's -// own, on top of the session's. +// own, added to the ones every call carries. const call_reply = async( s: Op_session, method: string, path: string, kind: Call_kind, body?: unknown, headers: Record = {}, ): Promise=>{ From 5558927e79a73bfd597c04476e25d91c2caf7c0b Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 17:00:34 -0700 Subject: [PATCH 07/24] test: the refused-cursor fixture says it follows Reply's API document The comment pointed at a pull request outside this repository; it now names the document itself. --- src/__tests__/operations/inbox-events.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/__tests__/operations/inbox-events.test.ts b/src/__tests__/operations/inbox-events.test.ts index ebbd3ef..6bf5dba 100644 --- a/src/__tests__/operations/inbox-events.test.ts +++ b/src/__tests__/operations/inbox-events.test.ts @@ -15,7 +15,7 @@ type Opts = {cursor?: string; since?: string; top?: string}; const events = async(opts: Opts = {})=>JSON.parse((await capture(()=>handle_inbox_events(opts, ctx(), {json: true}))).out); const failure = (opts: Opts)=>handle_inbox_events(opts, ctx(), {}).catch((x: unknown)=>x); -// How #477 publishes a cursor Reply will not read: a validation problem with no code, pointing at /cursor. +// How Reply's API document publishes a cursor it will not read: a validation problem with no code, pointing at /cursor. const CURSOR_TOO_OLD = { title: 'Validation failed', status: 400, detail: 'The request body contains validation errors.', errors: [{pointer: '/cursor', detail: '\'cursor\' is older than 30 days. Start again with \'since\' (at most 30 days ago) or with no parameters, which reads the last 30 days.'}], From 04f0486dc3465bde0729c75e05ef1bf0da283818 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 17:12:20 -0700 Subject: [PATCH 08/24] feat: send-email passes on what Reply rendered, the variables it could not fill and a reused send Reply now answers an email sent within the request with its subject and body as it filled them in, and the CLI passes them on as rendered_subject and rendered_body when Reply gives them; a send held for later has neither. A template variable Reply could not fill is contact.missing_variables, with the names under details.missing_variables, and a template Reply could not render is contact.rendering_failed with Reply's message as the detail. Neither sent anything. idempotency_key.reused may name the send the key was first taken for: reference, state and send_after go under details, each only when Reply gives it as a string, so a caller that built a repeat differently still learns which send holds the key. The handler sends trackLinks and trackOpens only when asked to track: Reply tracks neither unless asked, so a send without them is the request it always was. The flags follow. --- src/__tests__/operations/direct-send.test.ts | 96 ++++++++++++++++++++ src/__tests__/operations/options.test.ts | 11 ++- src/operations/direct-send.ts | 64 ++++++++++--- 3 files changed, 154 insertions(+), 17 deletions(-) diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index b6b724a..d90cff8 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -668,6 +668,17 @@ describe('a send for later', ()=>{ }); }); + it('adds the rendered subject and body of an email sent inside the request, each only when Reply gives it', async()=>{ + answer(accepted('send-email', {renderedSubject: 'Quick question, Marta', renderedBody: '

Hi Marta

', state: 'sent'})); + expect(await run('send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS)).toStrictEqual({ + status: 'sent', contact_id: 456, contact_created: false, message_id: null, sent_at: null, reply_status: 'new', + state: 'sent', rendered_subject: 'Quick question, Marta', rendered_body: '

Hi Marta

', + }); + mock_fetch.mockReset(); + answer(accepted('send-email', {reference: 'email-1001', state: 'queued', renderedSubject: null})); + expect(await run('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...LATER})).not.toHaveProperty('rendered_subject'); + }); + it('an answer without them prints exactly what it prints today, even when the flags were given', async()=>{ answer(accepted('linkedin-voice', {sentAtUtc: '2026-10-19T10:30:00Z'})); expect(await run('linkedin-voice', {script: SCRIPT}, {...LINKEDIN_OPTS, ...LATER})).toStrictEqual({ @@ -683,6 +694,7 @@ describe('a send for later', ()=>{ [{scheduleId: 'business'}, 'usage.id'], [{idempotencyKey: ''}, 'usage.idempotency_key'], [{idempotencyKey: 'k'.repeat(256)}, 'usage.idempotency_key'], + [{idempotencyKey: 'tab\there'}, 'usage.idempotency_key'], ]; for (const [name, message, opts] of SENDS) { @@ -746,6 +758,34 @@ describe('a send made with an idempotency key', ()=>{ } }); + it('a reused key carries the send Reply holds under it, reference, state and send_after, each only when Reply gives it', async()=>{ + for (const [name, message, opts, family] of SENDS) + { + mock_fetch.mockReset(); + answer(json({code: `${family}.idempotencyKeyReused`, detail: 'Reused.', reference: 'email-1001', state: 'queued', + sendAfter: '2026-11-03T14:00:00Z'}, 409)); + const e = await failure(name, message, opts); + expect(e, name).toMatchObject({code: 'idempotency_key.reused', + details: {reference: 'email-1001', state: 'queued', send_after: '2026-11-03T14:00:00Z'}}); + expect((e as {to_json: () => unknown}).to_json(), name).toMatchObject({error: {details: {reference: 'email-1001'}}}); + } + mock_fetch.mockReset(); + answer(json({code: 'contact.idempotencyKeyReused', reference: 'email-1001', state: 7, sendAfter: null}, 409)); + expect((await failure('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...KEY}) as {details?: unknown}).details) + .toStrictEqual({reference: 'email-1001'}); + }); + + it('a reused key without the send, and a key in use, carry no details: the output is what it was', async()=>{ + for (const reply_code of ['contact.idempotencyKeyReused', 'contact.idempotencyKeyInUse']) + { + mock_fetch.mockReset(); + answer(json({code: reply_code, detail: 'Conflict.', reference: reply_code.endsWith('InUse') ? 'email-1001' : undefined}, 409)); + const e = await failure('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...KEY}); + expect((e as {details?: unknown}).details, reply_code).toBeUndefined(); + expect(JSON.stringify((e as {to_json: () => unknown}).to_json()), reply_code).not.toContain('details'); + } + }); + it('reads those codes only under 409 and only in the send route\'s own family; any other answer is mapped as before', async()=>{ const cases: [Direct_send_name, unknown, Direct_send_opts, Response][] = [ ['send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...KEY}, json({code: 'contact.idempotencyKeyInUse'}, 400)], @@ -760,3 +800,59 @@ describe('a send made with an idempotency key', ()=>{ } }); }); + +describe('a direct email Reply renders', ()=>{ + const EMAIL: unknown = {subject: SUBJECT, body: BODY}; + + it('maps a variable Reply could not fill to contact.missing_variables, with the bare names under details', async()=>{ + answer(json({code: 'contact.missingVariables', detail: 'The message has variables with no value.', + missingVariables: ['FirstName', 'Company']}, 400)); + const e = await failure('send-email', EMAIL, EMAIL_OPTS); + expect(e).toMatchObject({code: 'contact.missing_variables', status: 400, exit_code: 1, reply_code: 'contact.missingVariables', + details: {missing_variables: ['FirstName', 'Company']}, ids: {contact_id: 456}}); + expect((e as {to_json: () => unknown}).to_json()).toMatchObject({error: {details: {missing_variables: ['FirstName', 'Company']}}}); + mock_fetch.mockReset(); + answer(json({code: 'contact.missingVariables', detail: 'The message has variables with no value.'}, 400)); + expect(await failure('send-email', EMAIL, EMAIL_OPTS)).toMatchObject({code: 'contact.missing_variables', + details: {missing_variables: []}}); + }); + + it('maps a template Reply could not render to contact.rendering_failed, with Reply\'s message as the detail', async()=>{ + answer(json({code: 'contact.renderingFailed', detail: 'Unclosed block at line 2.'}, 400)); + expect(await failure('send-email', EMAIL, EMAIL_OPTS)).toMatchObject({code: 'contact.rendering_failed', status: 400, exit_code: 1, + reply_code: 'contact.renderingFailed', detail: 'Unclosed block at line 2.'}); + }); + + it('reads the two codes only under 400; Reply\'s older contact.unknown stays reply.refused', async()=>{ + const cases: [Response, string][] = [ + [json({code: 'contact.missingVariables'}, 409), 'reply.refused'], + [json({code: 'contact.renderingFailed'}, 409), 'reply.refused'], + [json({code: 'contact.unknown', detail: 'The message has variables with no value.'}, 400), 'reply.refused'], + ]; + for (const [res, code] of cases) + { + mock_fetch.mockReset(); + answer(res); + expect(await failure('send-email', EMAIL, EMAIL_OPTS), code).toMatchObject({code, exit_code: 1}); + } + }); + + it('sends trackLinks and trackOpens only when their flags are given, and nothing of them otherwise', async()=>{ + const cases: [Direct_send_opts, Record][] = [ + [EMAIL_OPTS, {}], + [{...EMAIL_OPTS, trackLinks: true}, {trackLinks: true}], + [{...EMAIL_OPTS, trackOpens: true}, {trackOpens: true}], + [{...EMAIL_OPTS, trackLinks: true, trackOpens: true}, {trackLinks: true, trackOpens: true}], + ]; + for (const [opts, tracking] of cases) + { + mock_fetch.mockReset(); + answer(json({status: 'new', messageId: null})); + await run('send-email', EMAIL, opts); + const body = sent()[0].body as Record; + expect({trackLinks: body.trackLinks, trackOpens: body.trackOpens}, JSON.stringify(tracking)) + .toStrictEqual({trackLinks: tracking.trackLinks, trackOpens: tracking.trackOpens}); + expect(Object.keys(body).filter(k=>k.startsWith('track')), JSON.stringify(tracking)).toEqual(Object.keys(tracking)); + } + }); +}); diff --git a/src/__tests__/operations/options.test.ts b/src/__tests__/operations/options.test.ts index 25c1397..343b9f1 100644 --- a/src/__tests__/operations/options.test.ts +++ b/src/__tests__/operations/options.test.ts @@ -78,11 +78,14 @@ describe('operations/options', ()=>{ .toThrow('--send-after must be a date and time with its offset, e.g. 2026-11-03T14:00:00Z.'); }); - it('parse_idempotency_key takes 1 to 255 printable ASCII characters with no space at either end, as given', ()=>{ + it('parse_idempotency_key takes 1 to 255 characters from space to tilde, spaces inside, as given', ()=>{ expect(parse_idempotency_key('send-456-step-2')).toBe('send-456-step-2'); - expect(parse_idempotency_key('a b')).toBe('a b'); - expect(parse_idempotency_key('k'.repeat(255))).toBe('k'.repeat(255)); - for (const bad of ['', ' ', ' a', 'a ', 'k'.repeat(256), 'café', 'a\nb', 'a\tb']) + for (const good of ['a b', 'send 456 step 2', '~!"#', 'k'.repeat(255), `a${' '.repeat(253)}b`]) + { + expect(parse_idempotency_key(good), JSON.stringify(good)).toBe(good); + } + // A header value loses a space at either end on its way out, so such a key would reach Reply as another key. + for (const bad of ['', ' ', ' a', 'a ', 'k'.repeat(256), 'café', 'a\nb', 'a\tb', 'a\u007fb']) { expect(usage_code(()=>parse_idempotency_key(bad)), JSON.stringify(bad)).toBe('usage.idempotency_key'); } diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index c52e3de..afaafe1 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -12,7 +12,7 @@ import type {Cli_context} from '../context'; type Direct_send_name = 'send-email' | 'linkedin-connect' | 'linkedin-message' | 'linkedin-inmail' | 'linkedin-voice'; type Direct_send_opts = Contact_flags & { emailAccountId?: string; linkedinAccountId?: string; message?: string; - sendAfter?: string; scheduleId?: string; idempotencyKey?: string; + sendAfter?: string; scheduleId?: string; idempotencyKey?: string; trackLinks?: boolean; trackOpens?: boolean; }; type Text = Record; @@ -91,8 +91,30 @@ const read_text = (name: Direct_send_name, send: Direct_send, source: string | u return text; }; +// A refusal Reply publishes, under the status it comes with; details reads what the problem body +// carries beside its code, for the error output's details. +type Refusal = { + status: number; code: string; title: string; hint?: string; + details?: (body: Record) => Record | undefined; +}; + +// The keys a table names that hold a string in what Reply sent, under the names the CLI prints. +const picked = (keys: [string, string][], from: Record): Record=> + Object.fromEntries(keys.filter(([key])=>typeof from[key] === 'string').map(([key, to])=>[to, from[key]])); + +// A list of strings, or undefined for anything else. +const strings_of = (v: unknown): string[] | undefined=> + Array.isArray(v) && v.every(s=>typeof s === 'string') ? v : undefined; + // Reply's refusals of a direct send, by status and code. Each one is definite: nothing was sent. -const REFUSALS: Record = { +const REFUSALS: Record = { + 'contact.missingVariables': { + status: 400, code: 'contact.missing_variables', title: 'The email holds a template variable Reply could not fill, so nothing was sent.', + details: body=>({missing_variables: strings_of(body.missingVariables) ?? []}), + }, + 'contact.renderingFailed': { + status: 400, code: 'contact.rendering_failed', title: 'Reply could not render the email\'s template, so nothing was sent.', + }, 'contact.emailAccountNotFound': { status: 400, code: 'email_account.not_found', title: 'Reply has no mailbox by that id that this account can send from, so nothing was sent.', }, @@ -145,18 +167,22 @@ const REFUSALS: Record = const LIMITS: Record = {'directLinkedIn.dailyLimitReached': 'daily', 'directLinkedIn.weeklyLimitReached': 'weekly'}; -type Refusal = {status: number; code: string; title: string; hint?: string}; - // The codes of a send made for later, each Reply's code with the CLI code it maps to, here and // nowhere else. A send route answers a refused Idempotency-Key under its own family: contact for the // email, directLinkedIn for the LinkedIn sends. Neither sent anything. -const KEY_IN_USE = { +const KEY_IN_USE: Refusal = { status: 409, code: 'idempotency_key.in_use', title: 'Reply is still making an earlier send with this idempotency key, so this one sent nothing.', hint: 'Run it again with the same key once that send is made: Reply answers a repeat with the send the key first made.', }; -const KEY_REUSED = { +// Reply holds the send the key was first taken for, and may name it: a repeat built differently from +// the first attempt answers reused, so the caller still learns which send that was. +const KEY_REUSED: Refusal = { status: 409, code: 'idempotency_key.reused', title: 'Reply already took this idempotency key for a different send, so nothing was sent.', hint: 'Give each new send a key of its own.', + details: body=>{ + const held = picked(HELD_KEYS, body); + return Object.keys(held).length === 0 ? undefined : held; + }, }; const KEY_REFUSALS: Record> = { email: {'contact.idempotencyKeyInUse': KEY_IN_USE, 'contact.idempotencyKeyReused': KEY_REUSED}, @@ -184,7 +210,9 @@ const known_refusal = (a: Answer, table: Record): Operation_err const reply_code = reply_code_of(a); const known = reply_code === undefined ? undefined : table[reply_code]; return known !== undefined && known.status === a.status - ? new Operation_error(known.code, known.title, {status: a.status, reply_code, detail: detail_of(a), hint: known.hint}) + ? new Operation_error(known.code, known.title, { + status: a.status, reply_code, detail: detail_of(a), hint: known.hint, details: known.details?.(a.data as Record), + }) : undefined; }; @@ -208,12 +236,13 @@ const positive_integer = (v: unknown): number | null=> typeof v === 'number' && Number.isSafeInteger(v) && v > 0 ? v : null; // What Reply says of the send itself, each only when it gives it: the reference that names the send -// for direct-send get and cancel, the moment it was accepted for, and whether it has gone out. An -// answer without them is printed as it always was. -const LATER_KEYS: [string, string][] = [['reference', 'reference'], ['sendAfter', 'send_after'], ['state', 'state']]; +// for direct-send get and cancel, the moment it was accepted for, and whether it has gone out; and, +// for an email sent inside the request, its subject and body as Reply filled them in, before the +// signature and the tracking. An answer without them is printed as it always was. +const HELD_KEYS: [string, string][] = [['reference', 'reference'], ['sendAfter', 'send_after'], ['state', 'state']]; +const LATER_KEYS: [string, string][] = [...HELD_KEYS, ['renderedSubject', 'rendered_subject'], ['renderedBody', 'rendered_body']]; -const later_of = (sent: Record): Record=> - Object.fromEntries(LATER_KEYS.filter(([from])=>typeof sent[from] === 'string').map(([from, to])=>[to, sent[from]])); +const later_of = (sent: Record): Record=>picked(LATER_KEYS, sent); // What the CLI answers for a send Reply took: the contact it went to, as the add commands name it, so // a caller can keep its id. Neither adds a time of its own: Reply's answer to a direct email carries @@ -287,6 +316,15 @@ const handle_direct_send = async( { later.scheduleId = parse_id(opts.scheduleId, '--schedule-id'); } + // Reply tracks neither unless asked, so each is sent only to turn it on. + if (opts.trackLinks === true) + { + later.trackLinks = true; + } + if (opts.trackOpens === true) + { + later.trackOpens = true; + } const headers: Record = opts.idempotencyKey === undefined ? {} : {'Idempotency-Key': parse_idempotency_key(opts.idempotencyKey)}; const s = await open_session(ctx, g); @@ -353,5 +391,5 @@ const handle_direct_send = async( } }; -export {handle_direct_send, known_refusal, DIRECT_SEND_REFUSALS}; +export {handle_direct_send, known_refusal, strings_of, DIRECT_SEND_REFUSALS}; export type {Direct_send_name, Direct_send_opts}; From 3facee8901f845b234d4cba11ca102620f86c572 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 17:12:35 -0700 Subject: [PATCH 09/24] feat: direct-send get and cancel pass on the failure's code, the unfilled variables and the text Reply's model of a direct send now carries failureCode, missingVariables, renderedSubject and renderedBody. They are printed as failure_code, missing_variables, rendered_subject and rendered_body, each null when Reply gives none, as the other fields are. failure_reason stays a sentence for a person and is never read; failure_code is the one a caller branches on. missing_variables is printed only as a list of names, and as null for anything else. --- src/__tests__/operations/direct-sends.test.ts | 34 +++++++++++++++++-- src/operations/direct-sends.ts | 9 +++-- 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/src/__tests__/operations/direct-sends.test.ts b/src/__tests__/operations/direct-sends.test.ts index 20c163a..fd3af73 100644 --- a/src/__tests__/operations/direct-sends.test.ts +++ b/src/__tests__/operations/direct-sends.test.ts @@ -28,7 +28,8 @@ describe('direct-send get', ()=>{ answer(json(QUEUED)); expect(await get('email-1001')).toStrictEqual({ reference: 'email-1001', 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, + sent_at: null, message_id: null, failure_reason: null, failure_code: null, missing_variables: null, + rendered_subject: null, rendered_body: null, cancelled_at: null, }); expect(sent()).toEqual([{method: 'GET', url: 'https://api/v3/direct-sends/email-1001', body: undefined}]); }); @@ -38,10 +39,36 @@ describe('direct-send get', ()=>{ failureReason: 'notConnected'})); expect(await get('linkedin-1042')).toStrictEqual({ reference: 'linkedin-1042', channel: null, contact_id: null, state: 'held', send_after: null, - sent_at: '2026-11-03T14:00:02Z', message_id: 'm-1', failure_reason: 'notConnected', cancelled_at: null, + sent_at: '2026-11-03T14:00:02Z', message_id: 'm-1', failure_reason: 'notConnected', failure_code: null, + missing_variables: null, rendered_subject: null, rendered_body: null, cancelled_at: null, }); }); + it('gives what Reply says of a rendered or failed send as given: the failure\'s sentence and its code, the unfilled names', async()=>{ + answer(json({...QUEUED, state: 'failed', failureReason: 'A template variable had no value for this contact.', + failureCode: 'contact.missingVariables', missingVariables: ['FirstName', 'Company'], + renderedSubject: 'Quick question, Marta', renderedBody: '

Hi Marta

'})); + expect(await get('email-1001')).toMatchObject({ + state: 'failed', failure_reason: 'A template variable had no value for this contact.', failure_code: 'contact.missingVariables', + missing_variables: ['FirstName', 'Company'], rendered_subject: 'Quick question, Marta', rendered_body: '

Hi Marta

', + }); + }); + + it('gives missing_variables only as a list of names: anything else Reply sends there is null', async()=>{ + for (const missing of [[], ['FirstName']]) + { + mock_fetch.mockReset(); + answer(json({...QUEUED, missingVariables: missing})); + expect((await get('email-1001')).missing_variables, JSON.stringify(missing)).toEqual(missing); + } + for (const missing of ['FirstName', ['FirstName', 7], {name: 'FirstName'}, null]) + { + mock_fetch.mockReset(); + answer(json({...QUEUED, missingVariables: missing})); + expect((await get('email-1001')).missing_variables, JSON.stringify(missing)).toBeNull(); + } + }); + it('sends the reference as given, encoded into the path and never checked or parsed', async()=>{ for (const [reference, path] of [['ds_8F2k', 'ds_8F2k'], ['a/b c?d', 'a%2Fb%20c%3Fd'], ['email-0', 'email-0']]) { @@ -106,7 +133,8 @@ describe('direct-send cancel', ()=>{ answer(json(CANCELLED)); expect(await cancel('email-1001')).toStrictEqual({ reference: 'email-1001', channel: 'email', contact_id: 456, state: 'cancelled', send_after: '2026-11-03T14:00:00Z', - sent_at: null, message_id: null, failure_reason: null, cancelled_at: '2026-11-02T09:15:00Z', + sent_at: null, message_id: null, failure_reason: null, failure_code: null, missing_variables: null, + rendered_subject: null, rendered_body: null, cancelled_at: '2026-11-02T09:15:00Z', }); expect(sent()).toEqual([{method: 'POST', url: 'https://api/v3/direct-sends/email-1001/cancel', body: undefined}]); }); diff --git a/src/operations/direct-sends.ts b/src/operations/direct-sends.ts index eff6422..456e703 100644 --- a/src/operations/direct-sends.ts +++ b/src/operations/direct-sends.ts @@ -1,6 +1,6 @@ import {Unknown_outcome_error, UsageError} from '../utils/errors'; import {call_reply, expect_object, refusal, unreadable, open_session, type Answer} from './call'; -import {known_refusal, DIRECT_SEND_REFUSALS} from './direct-send'; +import {known_refusal, strings_of, DIRECT_SEND_REFUSALS} from './direct-send'; import {print_result} from './result'; import type {Op_globals} from './options'; import type {Cli_context} from '../context'; @@ -15,7 +15,8 @@ const path_of = (reference: string): string=>{ }; // A send as Reply holds it, under the CLI's names; a field 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. +// 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, and missing_variables is a list of names or null. const direct_send_of = (a: Answer, kind: 'read' | 'write'): Record=>{ const body = expect_object(a, kind); if (typeof body.reference !== 'string' || body.reference === '' || typeof body.state !== 'string' || body.state === '') @@ -26,7 +27,9 @@ const direct_send_of = (a: Answer, kind: 'read' | 'write'): Record Date: Wed, 28 Oct 2026 17:12:46 -0700 Subject: [PATCH 10/24] feat: inbox events maps a cursor or since past the feed's 30 days to inbox.cursor_expired Reply now refuses a cursor or a since older than the 30 days the feed keeps under a code of its own, inboxThread.eventWindowExpired, a 400 business problem. It maps to inbox.cursor_expired with Reply's detail and a hint to start again with --since, in one matcher that asks for both the status and the code. Every other refusal of the feed, an unreadable cursor included, is a validation problem without a code and maps as everywhere else, to reply.invalid_request with the field in details.fields, so the guess at the cursor's pointer that stood in for a code is gone. --- src/__tests__/operations/inbox-events.test.ts | 38 +++++++++++++------ src/__tests__/operations/program.test.ts | 6 +-- src/operations/inbox.ts | 23 +++++------ 3 files changed, 41 insertions(+), 26 deletions(-) diff --git a/src/__tests__/operations/inbox-events.test.ts b/src/__tests__/operations/inbox-events.test.ts index 6bf5dba..f692ec7 100644 --- a/src/__tests__/operations/inbox-events.test.ts +++ b/src/__tests__/operations/inbox-events.test.ts @@ -15,10 +15,15 @@ type Opts = {cursor?: string; since?: string; top?: string}; const events = async(opts: Opts = {})=>JSON.parse((await capture(()=>handle_inbox_events(opts, ctx(), {json: true}))).out); const failure = (opts: Opts)=>handle_inbox_events(opts, ctx(), {}).catch((x: unknown)=>x); -// How Reply's API document publishes a cursor it will not read: a validation problem with no code, pointing at /cursor. -const CURSOR_TOO_OLD = { +// A cursor or a since older than the feed's 30 days: a business problem with a code of its own. +const WINDOW_EXPIRED = { + code: 'inboxThread.eventWindowExpired', title: 'Event window expired', status: 400, + detail: 'The feed keeps 30 days. Start again with \'since\' (at most 30 days ago) or with no parameters, which reads the last 30 days.', +}; +// Any other cursor Reply will not read: a validation problem with no code, pointing at /cursor. +const CURSOR_UNREADABLE = { title: 'Validation failed', status: 400, detail: 'The request body contains validation errors.', - errors: [{pointer: '/cursor', detail: '\'cursor\' is older than 30 days. Start again with \'since\' (at most 30 days ago) or with no parameters, which reads the last 30 days.'}], + errors: [{pointer: '/cursor', detail: '\'cursor\' could not be read.'}], }; const problem = (body: unknown, status: number)=>json(body, status, {'Content-Type': 'application/problem+json'}); @@ -66,18 +71,27 @@ describe('inbox events', ()=>{ expect(mock_fetch).not.toHaveBeenCalled(); }); - it('a cursor Reply will not read is inbox.cursor_refused, which says to start again with --since', async()=>{ - answer(problem(CURSOR_TOO_OLD, 400)); - const e = await failure({cursor: 'AQjfObhYHZgAAADjVg'}); - expect(e).toMatchObject({code: 'inbox.cursor_refused', status: 400, exit_code: 1, details: {fields: ['cursor']}}); - expect((e as {reply_code?: string}).reply_code).toBeUndefined(); - expect((e as {hint?: string}).hint).toContain('--since'); + it('a cursor or a --since older than the feed keeps is inbox.cursor_expired, which says to start again with --since', async()=>{ + for (const opts of [{cursor: 'AQjfObhYHZgAAADjVg'}, {since: '2026-09-01T00:00:00Z'}, {}]) + { + mock_fetch.mockReset(); + answer(problem(WINDOW_EXPIRED, 400)); + const e = await failure(opts); + expect(e, JSON.stringify(opts)).toMatchObject({code: 'inbox.cursor_expired', status: 400, exit_code: 1, + reply_code: 'inboxThread.eventWindowExpired', detail: WINDOW_EXPIRED.detail}); + expect((e as {hint?: string}).hint, JSON.stringify(opts)).toContain('--since'); + } + }); + + it('the window\'s code under another status is not the window: it maps as everywhere else', async()=>{ + answer(problem({...WINDOW_EXPIRED, status: 409}, 409)); + expect(await failure({cursor: 'c'})).toMatchObject({code: 'reply.refused', reply_code: 'inboxThread.eventWindowExpired'}); }); - it('any other refusal maps as everywhere else', async()=>{ + it('any other refusal maps as everywhere else, a cursor Reply will not read included', async()=>{ const cases: [Opts, Response, string][] = [ - // The same pointer when no cursor was sent is not about one the caller holds. - [{since: '2026-11-03T14:00:00Z'}, problem(CURSOR_TOO_OLD, 400), 'reply.invalid_request'], + [{cursor: 'AQjfObhYHZgAAADjVg'}, problem(CURSOR_UNREADABLE, 400), 'reply.invalid_request'], + [{since: '2026-11-03T14:00:00Z'}, problem(CURSOR_UNREADABLE, 400), 'reply.invalid_request'], [{since: '2026-09-01T00:00:00Z'}, problem({title: 'Validation failed', status: 400, errors: [{pointer: '/since', detail: 'too old'}]}, 400), 'reply.invalid_request'], [{cursor: 'c'}, problem({code: 'inboxThread.invalidPagination', status: 400}, 400), 'reply.refused'], diff --git a/src/__tests__/operations/program.test.ts b/src/__tests__/operations/program.test.ts index 292463a..b9590b4 100644 --- a/src/__tests__/operations/program.test.ts +++ b/src/__tests__/operations/program.test.ts @@ -225,15 +225,15 @@ describe('the program', ()=>{ expect([init.method, url]).toEqual(['POST', 'https://api.reply.io/v3/direct-sends/email-1001/cancel']); }); - it('inbox events reads its flags through commander: both --cursor and --since exit 2, a refused cursor exits 1 with its code', async()=>{ + it('inbox events reads its flags through commander: both --cursor and --since exit 2, an expired cursor exits 1 with its code', async()=>{ const both = await run_program(['--json', '-q', '-k', 'key-1', 'inbox', 'events', '--cursor', 'c1', '--since', '2026-11-03T14:00:00Z']); expect(both.code).toBe(2); expect(mock_fetch).not.toHaveBeenCalled(); - answer(json({title: 'Validation failed', status: 400, errors: [{pointer: '/cursor', detail: 'older than 30 days'}]}, 400, + answer(json({code: 'inboxThread.eventWindowExpired', status: 400, detail: 'The feed keeps 30 days.'}, 400, {'Content-Type': 'application/problem+json'})); const {code, err} = await run_program(['--json', '-q', '-k', 'key-1', 'inbox', 'events', '--cursor', 'c1', '--top', '50']); expect(code).toBe(1); - expect(JSON.parse(err)).toMatchObject({error: {code: 'inbox.cursor_refused', status: 400}}); + expect(JSON.parse(err)).toMatchObject({error: {code: 'inbox.cursor_expired', status: 400, reply_code: 'inboxThread.eventWindowExpired'}}); expect((mock_fetch.mock.calls[0] as [string, RequestInit])[0]).toBe('https://api.reply.io/v3/inbox/events?cursor=c1&top=50'); }); diff --git a/src/operations/inbox.ts b/src/operations/inbox.ts index ffac791..f3074ee 100644 --- a/src/operations/inbox.ts +++ b/src/operations/inbox.ts @@ -1,7 +1,7 @@ import {Operation_error, UsageError} from '../utils/errors'; import { - call_reply, expect_object, read_page, refusal, reply_code_of, detail_of, invalid_fields, is_object, item_failure, unreadable, - open_session, type Answer, type Op_session, + call_reply, expect_object, read_page, refusal, reply_code_of, detail_of, is_object, item_failure, unreadable, open_session, + type Answer, type Op_session, } from './call'; import {parse_id, parse_int_in, parse_iso, parse_moment, parse_choice, type Op_globals} from './options'; import {print_result, with_ids} from './result'; @@ -68,13 +68,15 @@ const handle_inbox_list = async(opts: Inbox_list_opts, ctx: Cli_context, g: Op_g type Inbox_events_opts = {cursor?: string; since?: string; top?: string}; -// Reply refuses a cursor it will not read (unreadable, older than 30 days, or ahead of its clock) -// as a validation problem with no code that points at /cursor; the three differ only in their text. -const cursor_refused = (a: Answer, fields: string[]): Operation_error=> - new Operation_error('inbox.cursor_refused', 'Reply would not read the cursor: unreadable, older than 30 days or ahead of its clock.', { - status: a.status, detail: detail_of(a), details: {fields}, - hint: 'Start again with --since (at most 30 days ago), or with neither flag to read the last 30 days.', - }); +// The feed keeps 30 days. Reply refuses a cursor or a since older than that under a code of its own, +// the one refusal of the feed mapped here; any other is a validation problem and maps as everywhere else. +const window_expired = (a: Answer): Operation_error | undefined=> + a.status === 400 && reply_code_of(a) === 'inboxThread.eventWindowExpired' + ? new Operation_error('inbox.cursor_expired', 'Reply keeps the feed for 30 days, and the cursor or --since reaches further back.', { + status: a.status, reply_code: reply_code_of(a), detail: detail_of(a), + hint: 'Start again with --since at most 30 days ago, or with neither flag to read the last 30 days.', + }) + : undefined; const handle_inbox_events = async(opts: Inbox_events_opts, ctx: Cli_context, g: Op_globals): Promise=>{ if (opts.cursor !== undefined && opts.since !== undefined) @@ -105,8 +107,7 @@ const handle_inbox_events = async(opts: Inbox_events_opts, ctx: Cli_context, g: const a = await call_reply(s, 'GET', q === '' ? '/v3/inbox/events' : `/v3/inbox/events?${q}`, 'read'); if (a.status !== 200) { - const fields = opts.cursor !== undefined && a.status === 400 && reply_code_of(a) === undefined ? invalid_fields(a) : undefined; - throw fields?.includes('cursor') ? cursor_refused(a, fields) : refusal(a, 'read'); + throw window_expired(a) ?? refusal(a, 'read'); } const body = expect_object(a, 'read'); if (!Array.isArray(body.items) || typeof body.hasMore !== 'boolean' || typeof body.cursor !== 'string') From 477afebd1b38ab0f3cd15e2d44eb6b57f408b607 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 17:12:59 -0700 Subject: [PATCH 11/24] feat: send-email takes --track-links and --track-opens, and the help names the new answers send-email gains --track-links and --track-opens. Each is off unless given, as Reply tracks neither unless asked. Its help lists contact.missing_variables and contact.rendering_failed, says the unfilled names go under details.missing_variables, and says an email sent within the request adds rendered_subject and rendered_body. Every direct send's help says idempotency_key.reused names the send the key was first taken for under details. direct-send get and cancel list their new fields and say failure_reason is never parsed. inbox events lists inbox.cursor_expired in place of the earlier cursor code. --- src/__tests__/operations/commands.test.ts | 28 +++++++++++++++--- src/operations/commands.ts | 36 ++++++++++++++++------- 2 files changed, 49 insertions(+), 15 deletions(-) diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index 1ecc8d1..ac0bde6 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -47,6 +47,8 @@ describe('operations/commands', ()=>{ expect(flat, name).toContain('The reference is Reply\'s, from the answer of a send made with --send-after'); expect(flat, name).toContain('state is Reply\'s own word: queued or sending is not yet sent, then sent, failed or cancelled'); expect(flat, name).toContain('A Reply without this route answers reply.refused with status 404 and no reply_code'); + expect(flat, name).toContain('"failure_reason","failure_code","missing_variables","rendered_subject","rendered_body","cancelled_at"}'); + expect(flat, name).toContain('failure_reason is a sentence for a person, never parsed; failure_code is Reply\'s code for the failure'); } expect(help_of(sub(direct_send_command, 'cancel')).replace(/\s+/g, ' ')) .toContain('Cancelling a send already cancelled answers it again, so running it again is safe'); @@ -175,8 +177,10 @@ describe('operations/commands', ()=>{ expect(flat, text).toContain('Give --cursor or --since, not both; with neither, Reply reads the last 30 days'); expect(flat, text).toContain('loop on has_more, not on the number of items'); expect(flat, text).toContain('an empty page still carries a cursor'); - expect(flat, text).toContain('inbox.cursor_refused'); - expect(text, text).toContain(' inbox.cursor_refused\n'); + expect(flat, text).toContain('A cursor or a --since older than 30 days is inbox.cursor_expired: start again with --since'); + expect(flat, text).toContain('Any other cursor Reply will not read is reply.invalid_request with cursor in details.fields'); + expect(text, text).toContain(' inbox.cursor_expired\n'); + expect(text, text).not.toContain('cursor_refused'); expect(text, text).not.toContain('outcome.unknown'); }); @@ -236,7 +240,8 @@ describe('operations/commands', ()=>{ 'linkedin.feature_disabled', 'linkedin.account_inactive', 'linkedin.invalid_cookie']; 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'], + ['send-email', '--email-account-id', ['contact.not_found', ...IMPORT, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted', + 'contact.missing_variables', 'contact.rendering_failed'], '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], @@ -261,7 +266,8 @@ describe('operations/commands', ()=>{ for (const [name, account_flag, codes, sent_at] of DIRECT_SENDS) { const c = sub(contact_command, name); - expect(flags(c), name).toEqual([...CONTACT_FLAGS, account_flag, '--message', '--send-after', '--schedule-id', '--idempotency-key']); + expect(flags(c), name).toEqual([...CONTACT_FLAGS, account_flag, '--message', + ...(name === 'send-email' ? ['--track-links', '--track-opens'] : []), '--send-after', '--schedule-id', '--idempotency-key']); const text = help_of(c); const flat = text.replace(/\s+/g, ' '); expect(text, text).toContain('--message -'); @@ -285,6 +291,8 @@ describe('operations/commands', ()=>{ expect(flat, text).toContain('--idempotency-key goes as the Idempotency-Key header'); expect(flat, text).toContain('A Reply that knows the header answers a repeat with the same key with the send the key first made; while that one is still ' + 'being made the answer is idempotency_key.in_use, and the same key on a different send is idempotency_key.reused'); + expect(flat, text).toContain('idempotency_key.reused names the send the key was first taken for in details: reference, ' + + 'state and send_after, each only when Reply gives it'); // Exactly the codes its endpoint publishes, then the shared ones, as the help lists them. const listed = text.split('\nErrors')[1].split('\nExit codes')[0].split('\n').slice(1).map(l=>l.trim()); expect(listed, name).toEqual([...codes, 'idempotency_key.in_use', 'idempotency_key.reused', 'access.denied', 'access.feature_unavailable', 'rate_limited', 'reply.unavailable', @@ -292,6 +300,18 @@ describe('operations/commands', ()=>{ } }); + it('send-email says tracking is off unless asked, where the unfilled variables go, and what a rendered answer adds', ()=>{ + const c = sub(contact_command, 'send-email'); + const flat = help_of(c).replace(/\s+/g, ' '); + const described = (flag: string)=>c.options.find(o=>o.long === flag)?.description; + expect(described('--track-links'), '--track-links').toContain('Track the links'); + expect(described('--track-opens'), '--track-opens').toContain('Track the opens'); + expect(flat, flat).toContain('Reply tracks neither links nor opens unless --track-links or --track-opens asks it to'); + expect(flat, flat).toContain('contact.missing_variables names the variables Reply could not fill in details.missing_variables'); + expect(flat, flat).toContain('contact.rendering_failed is a template Reply could not render, its message in detail'); + expect(flat, flat).toContain('An email sent within the request adds rendered_subject and rendered_body'); + }); + it('inbox reply takes its text only through --message, and says a repeat may send it twice', ()=>{ const reply = sub(inbox_command, 'reply'); expect(flags(reply)).toEqual(['--message']); diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 7200302..3040cd9 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -305,7 +305,9 @@ const LATER = 'With --send-after Reply holds the send until that moment, given w + 'answer without state comes from a Reply that does not know --send-after and --schedule-id: it sent at once, as\n' + 'without them. --idempotency-key goes as the Idempotency-Key header, never in the body. A Reply that knows the header\n' + 'answers a repeat with the same key with the send the key first made; while that one is still being made the answer\n' - + 'is idempotency_key.in_use, and the same key on a different send is idempotency_key.reused. Neither sends anything.\n'; + + 'is idempotency_key.in_use, and the same key on a different send is idempotency_key.reused. Neither sends anything.\n' + + 'idempotency_key.reused names the send the key was first taken for in details: reference, state and send_after, each\n' + + 'only when Reply gives it.\n'; // The refusals of a send's key, the same on every direct send, after each send's own. const KEY_CODES = ['idempotency_key.in_use', 'idempotency_key.reused']; @@ -318,17 +320,25 @@ const ANN_PROFILE = '{"linkedin_url":"https://www.linkedin.com/in/ann-example"," 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') + .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') .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')], - ['contact.not_found', ...IMPORT_CODES, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted', ...KEY_CODES], true, + ['contact.not_found', ...IMPORT_CODES, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted', + 'contact.missing_variables', 'contact.rendering_failed', ...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' + 'The email is read from stdin only, so its text never sits in the argument list. The body is HTML. Without\n' + '--send-after, Reply sends a direct email at once, outside the mailbox\'s daily limit and sending delay.\n' + + 'Reply tracks neither links nor opens unless --track-links or --track-opens asks it to. An email sent within the\n' + + 'request adds rendered_subject and rendered_body, the subject and body as Reply filled them in, when Reply gives\n' + + 'them; a send held for later has neither. contact.missing_variables names the variables Reply could not fill in\n' + + 'details.missing_variables, and contact.rendering_failed is a template Reply could not render, its message in\n' + + 'detail. Neither sends anything.\n' + LATER + SENT_TO('email', 'email'), SEND_TWICE('email'))) .action(run(async(cmd)=>{ @@ -433,14 +443,15 @@ inbox_command.command('events') .option('--top ', 'Items per page, 1-1000 (default: Reply\'s)') .description('One page of the inbox feed: each thread whose latest message changed, oldest first, read forward by cursor') .addHelpText('after', help([ex('inbox events --since 2026-11-01T00:00:00Z'), ex('inbox events --cursor AQjfObhYHZgAAADjVg --top 200')], - ['inbox.cursor_refused'], false, + ['inbox.cursor_expired'], false, 'Result: {"items","has_more","cursor"}, the items as Reply gives them, one per thread whose latest message, inbound\n' + 'or outbound, changed: threadId, contactId, channel, lastActivityDate, flags (hasReply, hasBounce, hasAutoReply,\n' + 'hasOutOfOffice) and lastMessage among them. Give --cursor or --since, not both; with neither, Reply reads the last\n' + '30 days. Call again with the answered cursor while has_more is true, and loop on has_more, not on the number of\n' + 'items: an empty page still carries a cursor, and when has_more is false that cursor is where the next read starts.\n' - + '--since goes to Reply in UTC; a moment without its offset is refused (usage.date). A cursor Reply will not read,\n' - + 'one unreadable, older than 30 days or ahead of its clock, is inbox.cursor_refused: start again with --since.\n' + + '--since goes to Reply in UTC; a moment without its offset is refused (usage.date). A cursor or a --since older\n' + + 'than 30 days is inbox.cursor_expired: start again with --since. Any other cursor Reply will not read is\n' + + 'reply.invalid_request with cursor in details.fields.\n' + 'A Reply without the feed answers reply.refused with status 404 and no reply_code.\n')) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); @@ -562,11 +573,14 @@ schedule_command.command('list') const direct_send_command = new Command('direct-send').description('Read or cancel a direct send Reply holds to send later'); -const DIRECT_SEND = 'Result: {"reference","channel","contact_id","state","send_after","sent_at","message_id","failure_reason",\n' - + '"cancelled_at"}, Reply\'s fields under these names, each null when Reply gives none. The reference is Reply\'s, from the\n' - + 'answer of a send made with --send-after; it is passed on as given and never read. state is Reply\'s own word: queued\n' - + 'or sending is not yet sent, then sent, failed or cancelled. A Reply without this route answers reply.refused with\n' - + 'status 404 and no reply_code; direct_send.not_found is a reference that Reply has no send for.\n'; +const DIRECT_SEND = 'Result: {"reference","channel","contact_id","state","send_after","sent_at","message_id",\n' + + '"failure_reason","failure_code","missing_variables","rendered_subject","rendered_body","cancelled_at"}, Reply\'s fields\n' + + 'under these names, each null when Reply gives none. The reference is Reply\'s, from the answer of a send made with --send-after; it is\n' + + 'passed on as given and never read. state is Reply\'s own word: queued or sending is not yet sent, then sent, failed or\n' + + 'cancelled. failure_reason is a sentence for a person, never parsed; failure_code is Reply\'s code for the failure,\n' + + 'the one to branch on. missing_variables lists the template variables Reply could not fill, and rendered_subject and\n' + + 'rendered_body are the text as Reply filled it in. A Reply without this route answers reply.refused with status 404\n' + + 'and no reply_code; direct_send.not_found is a reference that Reply has no send for.\n'; direct_send_command.command('get') .argument('', 'The send\'s reference, as a send made with --send-after answered it') From b5f83c4bdb1765356fd5f76f292ddcb40b36a881 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 17:13:47 -0700 Subject: [PATCH 12/24] docs: the README names the rendered text, tracking, the unfilled variables and the expired feed The direct sends section now says send-email tracks nothing unless --track-links or --track-opens asks it to, that an email sent within the request adds rendered_subject and rendered_body, where contact.missing_variables puts the names, and what contact.rendering_failed carries. It says what idempotency_key.reused names under details and which keys are taken. direct-send get and cancel list every field they answer, and inbox events names inbox.cursor_expired for a cursor or a since past the feed's 30 days. --- README.md | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index c13f6b4..4860eba 100644 --- a/README.md +++ b/README.md @@ -198,7 +198,7 @@ prints JSON (indented; compact with `--json`) and says what happened in a stable | `reply contact update ( \| ) --fields -` | change some fields and custom fields; null clears one → `updated` | | `reply contact delete ` | → `deleted` | | `reply contact opt-out ` | → `opted_out` | -| `reply contact send-email --email-account-id N --message -` | one email outside any sequence → `sent` | +| `reply contact send-email --email-account-id N --message - [--track-links] [--track-opens]` | one email outside any sequence → `sent` | | `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` | @@ -308,6 +308,17 @@ lengths Reply publishes (a LinkedIn message's 8000 characters, an InMail's 200 a 1000) are refused before anything is sent. Reply reads `{{…}}` in a LinkedIn text as its template variables, and refuses one it cannot fill with `linkedin.missing_variables`. +`contact send-email` tracks neither links nor opens unless `--track-links` or `--track-opens` asks +it to. An email Reply sends within the request adds `rendered_subject` and `rendered_body`, the text +as Reply filled it in, when Reply gives them; a send held for later has neither. A template variable +Reply cannot fill is `contact.missing_variables`, with the names under the error's +`details.missing_variables`, and a template Reply cannot render is `contact.rendering_failed`, with +Reply's message as its `detail`. Neither sends anything: + +```sh +# {"error":{"code":"contact.missing_variables",…,"details":{"missing_variables":["FirstName","Company"]}}} +``` + 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 offset is refused @@ -322,7 +333,10 @@ comes from a Reply that does not know these flags yet: it sent at once, as witho `--idempotency-key` goes to Reply as the `Idempotency-Key` header, never in the body. A Reply that knows the header answers a repeat with the same key with the send the key first made; while that one is still being made the answer is `idempotency_key.in_use`, and the same key on a different -send is `idempotency_key.reused`. Neither sends anything. +send is `idempotency_key.reused`. Neither sends anything. `idempotency_key.reused` names the send +the key was first taken for under the error's `details`: its `reference`, `state` and `send_after`, +each only when Reply gives it. A key is 1 to 255 printable ASCII characters; a space inside is kept, +and one at either end is refused (`usage.idempotency_key`), since a header loses it on the way out. ```sh echo '{"body":"Following up on my note."}' | reply contact linkedin-message --contact-id 456 --linkedin-account-id 34 --message - --send-after 2026-11-03T14:00:00Z --idempotency-key follow-up-456-1 @@ -331,17 +345,22 @@ reply direct-send get linkedin-1042 reply direct-send cancel linkedin-1042 ``` -`direct-send cancel` of a send already cancelled answers it again. A send already gone out or -failed is `direct_send.already_sent` or `direct_send.already_failed`, and a reference Reply has no -send for is `direct_send.not_found`. +Both answer the send under the CLI's names, each null when Reply gives none: `reference`, +`channel`, `contact_id`, `state`, `send_after`, `sent_at`, `message_id`, `failure_reason`, +`failure_code`, `missing_variables`, `rendered_subject`, `rendered_body` and `cancelled_at`. +`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. `direct-send cancel` of a send already cancelled answers it +again. A send already gone out or failed is `direct_send.already_sent` or +`direct_send.already_failed`, and a reference Reply has no send for is `direct_send.not_found`. `reply inbox events` reads the inbox feed forward. Each page holds the threads whose latest message, inbound or outbound, changed, oldest first and as Reply gives them, with `has_more` and a `cursor`. Start with `--since ` (inclusive, at most 30 days ago) or with neither flag, which reads the last 30 days, then pass the answered cursor back with `--cursor` while `has_more` is true. Loop on `has_more`, not on the number of items: an empty page still carries a cursor, and when `has_more` is -false that cursor is where the next read starts. A cursor Reply will not read, one unreadable, older -than 30 days or ahead of its clock, is `inbox.cursor_refused`: start again with `--since`. +false that cursor is where the next read starts. A cursor or a `--since` older than the 30 days the +feed keeps is `inbox.cursor_expired`: start again with `--since`. Any other cursor Reply will not +read is `reply.invalid_request`, with `cursor` in `details.fields`. ```sh reply inbox events --since 2026-11-01T00:00:00Z --json From 91a97ef148dc8fad9f49b1f6801ff63fec1a2c45 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 17:23:01 -0700 Subject: [PATCH 13/24] fix: inbox events keeps inbox.cursor_refused for a cursor Reply will not read, beside the window Reply publishes a cursor it will not read, unreadable or ahead of its clock, as a validation problem with no code that points at /cursor. That form is again inbox.cursor_refused, with the field in details.fields, when a cursor was sent. The window's own code, eventWindowExpired, is still inbox.cursor_expired and is matched first. Both give the same hint, to start again with --since, from one constant, and both are listed in inbox events --help and the README. --- README.md | 5 +++-- src/__tests__/operations/commands.test.ts | 5 ++--- src/__tests__/operations/inbox-events.test.ts | 16 +++++++++++--- src/operations/commands.ts | 6 ++--- src/operations/inbox.ts | 22 +++++++++++++------ 5 files changed, 36 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 4860eba..f3dd244 100644 --- a/README.md +++ b/README.md @@ -359,8 +359,9 @@ Start with `--since ` (inclusive, at most 30 days ago) or with neither f last 30 days, then pass the answered cursor back with `--cursor` while `has_more` is true. Loop on `has_more`, not on the number of items: an empty page still carries a cursor, and when `has_more` is false that cursor is where the next read starts. A cursor or a `--since` older than the 30 days the -feed keeps is `inbox.cursor_expired`: start again with `--since`. Any other cursor Reply will not -read is `reply.invalid_request`, with `cursor` in `details.fields`. +feed keeps is `inbox.cursor_expired`: start again with `--since`. A cursor Reply will not read +otherwise, unreadable or ahead of its clock, is `inbox.cursor_refused`, with `cursor` in +`details.fields`; start again the same way. ```sh reply inbox events --since 2026-11-01T00:00:00Z --json diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index ac0bde6..a133b3f 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -178,9 +178,8 @@ describe('operations/commands', ()=>{ expect(flat, text).toContain('loop on has_more, not on the number of items'); expect(flat, text).toContain('an empty page still carries a cursor'); expect(flat, text).toContain('A cursor or a --since older than 30 days is inbox.cursor_expired: start again with --since'); - expect(flat, text).toContain('Any other cursor Reply will not read is reply.invalid_request with cursor in details.fields'); - expect(text, text).toContain(' inbox.cursor_expired\n'); - expect(text, text).not.toContain('cursor_refused'); + expect(flat, text).toContain('A cursor Reply will not read otherwise, unreadable or ahead of its clock, is inbox.cursor_refused'); + expect(text, text).toContain(' inbox.cursor_expired\n inbox.cursor_refused\n'); expect(text, text).not.toContain('outcome.unknown'); }); diff --git a/src/__tests__/operations/inbox-events.test.ts b/src/__tests__/operations/inbox-events.test.ts index f692ec7..93bda50 100644 --- a/src/__tests__/operations/inbox-events.test.ts +++ b/src/__tests__/operations/inbox-events.test.ts @@ -20,7 +20,7 @@ const WINDOW_EXPIRED = { code: 'inboxThread.eventWindowExpired', title: 'Event window expired', status: 400, detail: 'The feed keeps 30 days. Start again with \'since\' (at most 30 days ago) or with no parameters, which reads the last 30 days.', }; -// Any other cursor Reply will not read: a validation problem with no code, pointing at /cursor. +// How Reply's API document publishes a cursor it will not read: a validation problem with no code, pointing at /cursor. const CURSOR_UNREADABLE = { title: 'Validation failed', status: 400, detail: 'The request body contains validation errors.', errors: [{pointer: '/cursor', detail: '\'cursor\' could not be read.'}], @@ -88,9 +88,19 @@ describe('inbox events', ()=>{ expect(await failure({cursor: 'c'})).toMatchObject({code: 'reply.refused', reply_code: 'inboxThread.eventWindowExpired'}); }); - it('any other refusal maps as everywhere else, a cursor Reply will not read included', async()=>{ + it('a cursor Reply will not read is inbox.cursor_refused, with the same hint as the expired window', async()=>{ + answer(problem(CURSOR_UNREADABLE, 400)); + const e = await failure({cursor: 'AQjfObhYHZgAAADjVg'}); + expect(e).toMatchObject({code: 'inbox.cursor_refused', status: 400, exit_code: 1, details: {fields: ['cursor']}}); + expect((e as {reply_code?: string}).reply_code).toBeUndefined(); + mock_fetch.mockReset(); + answer(problem(WINDOW_EXPIRED, 400)); + expect((e as {hint?: string}).hint).toBe((await failure({cursor: 'AQjfObhYHZgAAADjVg'}) as {hint?: string}).hint); + }); + + it('any other refusal maps as everywhere else', async()=>{ const cases: [Opts, Response, string][] = [ - [{cursor: 'AQjfObhYHZgAAADjVg'}, problem(CURSOR_UNREADABLE, 400), 'reply.invalid_request'], + // The same pointer when no cursor was sent is not about one the caller holds. [{since: '2026-11-03T14:00:00Z'}, problem(CURSOR_UNREADABLE, 400), 'reply.invalid_request'], [{since: '2026-09-01T00:00:00Z'}, problem({title: 'Validation failed', status: 400, errors: [{pointer: '/since', detail: 'too old'}]}, 400), 'reply.invalid_request'], diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 3040cd9..7f90a66 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -443,15 +443,15 @@ inbox_command.command('events') .option('--top ', 'Items per page, 1-1000 (default: Reply\'s)') .description('One page of the inbox feed: each thread whose latest message changed, oldest first, read forward by cursor') .addHelpText('after', help([ex('inbox events --since 2026-11-01T00:00:00Z'), ex('inbox events --cursor AQjfObhYHZgAAADjVg --top 200')], - ['inbox.cursor_expired'], false, + ['inbox.cursor_expired', 'inbox.cursor_refused'], false, 'Result: {"items","has_more","cursor"}, the items as Reply gives them, one per thread whose latest message, inbound\n' + 'or outbound, changed: threadId, contactId, channel, lastActivityDate, flags (hasReply, hasBounce, hasAutoReply,\n' + 'hasOutOfOffice) and lastMessage among them. Give --cursor or --since, not both; with neither, Reply reads the last\n' + '30 days. Call again with the answered cursor while has_more is true, and loop on has_more, not on the number of\n' + 'items: an empty page still carries a cursor, and when has_more is false that cursor is where the next read starts.\n' + '--since goes to Reply in UTC; a moment without its offset is refused (usage.date). A cursor or a --since older\n' - + 'than 30 days is inbox.cursor_expired: start again with --since. Any other cursor Reply will not read is\n' - + 'reply.invalid_request with cursor in details.fields.\n' + + 'than 30 days is inbox.cursor_expired: start again with --since. A cursor Reply will not read otherwise,\n' + + 'unreadable or ahead of its clock, is inbox.cursor_refused, with cursor in details.fields; start again the same way.\n' + 'A Reply without the feed answers reply.refused with status 404 and no reply_code.\n')) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); diff --git a/src/operations/inbox.ts b/src/operations/inbox.ts index f3074ee..dce533f 100644 --- a/src/operations/inbox.ts +++ b/src/operations/inbox.ts @@ -1,7 +1,7 @@ import {Operation_error, UsageError} from '../utils/errors'; import { - call_reply, expect_object, read_page, refusal, reply_code_of, detail_of, is_object, item_failure, unreadable, open_session, - type Answer, type Op_session, + call_reply, expect_object, read_page, refusal, reply_code_of, detail_of, invalid_fields, is_object, item_failure, unreadable, + open_session, type Answer, type Op_session, } from './call'; import {parse_id, parse_int_in, parse_iso, parse_moment, parse_choice, type Op_globals} from './options'; import {print_result, with_ids} from './result'; @@ -68,16 +68,23 @@ const handle_inbox_list = async(opts: Inbox_list_opts, ctx: Cli_context, g: Op_g type Inbox_events_opts = {cursor?: string; since?: string; top?: string}; -// The feed keeps 30 days. Reply refuses a cursor or a since older than that under a code of its own, -// the one refusal of the feed mapped here; any other is a validation problem and maps as everywhere else. +const START_AGAIN = 'Start again with --since (at most 30 days ago), or with neither flag to read the last 30 days.'; + +// The feed keeps 30 days. Reply refuses a cursor or a since older than that under a code of its own. const window_expired = (a: Answer): Operation_error | undefined=> a.status === 400 && reply_code_of(a) === 'inboxThread.eventWindowExpired' ? new Operation_error('inbox.cursor_expired', 'Reply keeps the feed for 30 days, and the cursor or --since reaches further back.', { - status: a.status, reply_code: reply_code_of(a), detail: detail_of(a), - hint: 'Start again with --since at most 30 days ago, or with neither flag to read the last 30 days.', + status: a.status, reply_code: reply_code_of(a), detail: detail_of(a), hint: START_AGAIN, }) : undefined; +// Any other cursor Reply will not read (unreadable, or ahead of its clock) is a validation problem +// with no code that points at /cursor; they differ only in their text. +const cursor_refused = (a: Answer, fields: string[]): Operation_error=> + new Operation_error('inbox.cursor_refused', 'Reply would not read the cursor: unreadable, older than 30 days or ahead of its clock.', { + status: a.status, detail: detail_of(a), details: {fields}, hint: START_AGAIN, + }); + const handle_inbox_events = async(opts: Inbox_events_opts, ctx: Cli_context, g: Op_globals): Promise=>{ if (opts.cursor !== undefined && opts.since !== undefined) { @@ -107,7 +114,8 @@ const handle_inbox_events = async(opts: Inbox_events_opts, ctx: Cli_context, g: const a = await call_reply(s, 'GET', q === '' ? '/v3/inbox/events' : `/v3/inbox/events?${q}`, 'read'); if (a.status !== 200) { - throw window_expired(a) ?? refusal(a, 'read'); + const fields = opts.cursor !== undefined && a.status === 400 && reply_code_of(a) === undefined ? invalid_fields(a) : undefined; + throw window_expired(a) ?? (fields?.includes('cursor') ? cursor_refused(a, fields) : refusal(a, 'read')); } const body = expect_object(a, 'read'); if (!Array.isArray(body.items) || typeof body.hasMore !== 'boolean' || typeof body.cursor !== 'string') From 4ff83c290e35188ad2aabebe322299744d3b7ac8 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 17:23:09 -0700 Subject: [PATCH 14/24] fix: direct-send get and cancel add the rendered text, failure code and unfilled names when given An answer from a Reply without failureCode, missingVariables, renderedSubject and renderedBody now prints exactly as it did before them, instead of carrying four new nulls. Each is added when Reply gives it: failure_code, rendered_subject and rendered_body as text or null, and missing_variables as a list of names or null. A value of any other shape is left out. The fields that were there before keep printing null when Reply leaves them out. --- README.md | 8 ++--- src/__tests__/operations/commands.test.ts | 2 +- src/__tests__/operations/direct-sends.test.ts | 32 +++++++++++++------ src/operations/commands.ts | 17 +++++----- src/operations/direct-sends.ts | 23 ++++++++++--- 5 files changed, 54 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index f3dd244..916053a 100644 --- a/README.md +++ b/README.md @@ -346,10 +346,10 @@ reply direct-send cancel linkedin-1042 ``` Both answer the send under the CLI's names, each null when Reply gives none: `reference`, -`channel`, `contact_id`, `state`, `send_after`, `sent_at`, `message_id`, `failure_reason`, -`failure_code`, `missing_variables`, `rendered_subject`, `rendered_body` and `cancelled_at`. -`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. `direct-send cancel` of a send already cancelled answers it +`channel`, `contact_id`, `state`, `send_after`, `sent_at`, `message_id`, `failure_reason` and +`cancelled_at`. `failure_code`, `missing_variables`, `rendered_subject` and `rendered_body` are +added only when Reply gives them. `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. `direct-send cancel` of a send already cancelled answers it again. A send already gone out or failed is `direct_send.already_sent` or `direct_send.already_failed`, and a reference Reply has no send for is `direct_send.not_found`. diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index a133b3f..82e8a6c 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -47,7 +47,7 @@ describe('operations/commands', ()=>{ expect(flat, name).toContain('The reference is Reply\'s, from the answer of a send made with --send-after'); expect(flat, name).toContain('state is Reply\'s own word: queued or sending is not yet sent, then sent, failed or cancelled'); expect(flat, name).toContain('A Reply without this route answers reply.refused with status 404 and no reply_code'); - expect(flat, name).toContain('"failure_reason","failure_code","missing_variables","rendered_subject","rendered_body","cancelled_at"}'); + expect(flat, name).toContain('failure_code, missing_variables, rendered_subject and rendered_body are added only when Reply gives them'); expect(flat, name).toContain('failure_reason is a sentence for a person, never parsed; failure_code is Reply\'s code for the failure'); } expect(help_of(sub(direct_send_command, 'cancel')).replace(/\s+/g, ' ')) diff --git a/src/__tests__/operations/direct-sends.test.ts b/src/__tests__/operations/direct-sends.test.ts index fd3af73..ec9ddcc 100644 --- a/src/__tests__/operations/direct-sends.test.ts +++ b/src/__tests__/operations/direct-sends.test.ts @@ -28,8 +28,7 @@ describe('direct-send get', ()=>{ answer(json(QUEUED)); expect(await get('email-1001')).toStrictEqual({ reference: 'email-1001', channel: 'email', contact_id: 456, state: 'queued', send_after: '2026-11-03T14:00:00Z', - sent_at: null, message_id: null, failure_reason: null, failure_code: null, missing_variables: null, - rendered_subject: null, rendered_body: null, cancelled_at: null, + sent_at: null, message_id: null, failure_reason: null, cancelled_at: null, }); expect(sent()).toEqual([{method: 'GET', url: 'https://api/v3/direct-sends/email-1001', body: undefined}]); }); @@ -39,8 +38,7 @@ describe('direct-send get', ()=>{ failureReason: 'notConnected'})); expect(await get('linkedin-1042')).toStrictEqual({ reference: 'linkedin-1042', channel: null, contact_id: null, state: 'held', send_after: null, - sent_at: '2026-11-03T14:00:02Z', message_id: 'm-1', failure_reason: 'notConnected', failure_code: null, - missing_variables: null, rendered_subject: null, rendered_body: null, cancelled_at: null, + sent_at: '2026-11-03T14:00:02Z', message_id: 'm-1', failure_reason: 'notConnected', cancelled_at: null, }); }); @@ -54,18 +52,33 @@ describe('direct-send get', ()=>{ }); }); - it('gives missing_variables only as a list of names: anything else Reply sends there is null', async()=>{ + it('adds the rendered text, the failure\'s code and the unfilled names only when Reply gives them, a null included', async()=>{ + answer(json({...QUEUED, failureCode: null, missingVariables: null, renderedSubject: null, renderedBody: null})); + expect(await get('email-1001')).toMatchObject({failure_code: null, missing_variables: null, rendered_subject: null, rendered_body: null}); + for (const [from, to] of [['failureCode', 'failure_code'], ['missingVariables', 'missing_variables'], + ['renderedSubject', 'rendered_subject'], ['renderedBody', 'rendered_body']]) + { + mock_fetch.mockReset(); + answer(json({...QUEUED, failureCode: 'x', missingVariables: [], renderedSubject: 's', renderedBody: 'b', [from]: undefined})); + const got = await get('email-1001'); + expect(got, from).not.toHaveProperty(to); + expect(Object.keys(got), from).toHaveLength(12); + } + }); + + 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']]) { mock_fetch.mockReset(); answer(json({...QUEUED, missingVariables: missing})); expect((await get('email-1001')).missing_variables, JSON.stringify(missing)).toEqual(missing); } - for (const missing of ['FirstName', ['FirstName', 7], {name: 'FirstName'}, null]) + for (const odd of ['FirstName', ['FirstName', 7], {name: 'FirstName'}, 7]) { mock_fetch.mockReset(); - answer(json({...QUEUED, missingVariables: missing})); - expect((await get('email-1001')).missing_variables, JSON.stringify(missing)).toBeNull(); + answer(json({...QUEUED, missingVariables: odd, failureCode: [odd], renderedSubject: 7, renderedBody: {odd}})); + expect(Object.keys(await get('email-1001')), JSON.stringify(odd)).toEqual(['reference', 'channel', 'contact_id', 'state', + 'send_after', 'sent_at', 'message_id', 'failure_reason', 'cancelled_at']); } }); @@ -133,8 +146,7 @@ describe('direct-send cancel', ()=>{ answer(json(CANCELLED)); expect(await cancel('email-1001')).toStrictEqual({ reference: 'email-1001', channel: 'email', contact_id: 456, state: 'cancelled', send_after: '2026-11-03T14:00:00Z', - sent_at: null, message_id: null, failure_reason: null, failure_code: null, missing_variables: null, - rendered_subject: null, rendered_body: null, cancelled_at: '2026-11-02T09:15:00Z', + sent_at: null, message_id: null, failure_reason: null, cancelled_at: '2026-11-02T09:15:00Z', }); expect(sent()).toEqual([{method: 'POST', url: 'https://api/v3/direct-sends/email-1001/cancel', body: undefined}]); }); diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 7f90a66..9f989c3 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -573,14 +573,15 @@ schedule_command.command('list') const direct_send_command = new Command('direct-send').description('Read or cancel a direct send Reply holds to send later'); -const DIRECT_SEND = 'Result: {"reference","channel","contact_id","state","send_after","sent_at","message_id",\n' - + '"failure_reason","failure_code","missing_variables","rendered_subject","rendered_body","cancelled_at"}, Reply\'s fields\n' - + 'under these names, each null when Reply gives none. The reference is Reply\'s, from the answer of a send made with --send-after; it is\n' - + 'passed on as given and never read. state is Reply\'s own word: queued or sending is not yet sent, then sent, failed or\n' - + 'cancelled. failure_reason is a sentence for a person, never parsed; failure_code is Reply\'s code for the failure,\n' - + 'the one to branch on. missing_variables lists the template variables Reply could not fill, and rendered_subject and\n' - + 'rendered_body are the text as Reply filled it in. A Reply without this route answers reply.refused with status 404\n' - + 'and no reply_code; direct_send.not_found is a reference that Reply has no send for.\n'; +const DIRECT_SEND = 'Result: {"reference","channel","contact_id","state","send_after","sent_at","message_id","failure_reason",\n' + + '"cancelled_at"}, Reply\'s fields under these names, each null when Reply gives none. The reference is Reply\'s, from the\n' + + 'answer of a send made with --send-after; it is passed on as given and never read. state is Reply\'s own word: queued\n' + + 'or sending is not yet sent, then sent, failed or cancelled. failure_code, missing_variables, rendered_subject and\n' + + 'rendered_body are added only when Reply gives them: failure_reason is a sentence for a person, never parsed;\n' + + 'failure_code is Reply\'s code for the failure, the one to branch on. missing_variables lists the template variables\n' + + 'Reply could not fill, and rendered_subject and rendered_body are the text as Reply filled it in. A Reply without this\n' + + 'route answers reply.refused with status 404 and no reply_code; direct_send.not_found is a reference that Reply has no\n' + + 'send for.\n'; direct_send_command.command('get') .argument('', 'The send\'s reference, as a send made with --send-after answered it') diff --git a/src/operations/direct-sends.ts b/src/operations/direct-sends.ts index 456e703..0f2ab1c 100644 --- a/src/operations/direct-sends.ts +++ b/src/operations/direct-sends.ts @@ -14,9 +14,24 @@ const path_of = (reference: string): string=>{ return `/v3/direct-sends/${encodeURIComponent(reference)}`; }; -// A send as Reply holds it, under the CLI's names; a field Reply leaves out is null. Its state is Reply's word, passed on as given, so a state the CLI does +// What Reply says of the text it rendered and of a failure's code, each only when it gives it, as text +// or null, and the unfilled names as a list: an answer without them prints as it did before them. +const RENDERING_KEYS: [string, string][] = [['failureCode', 'failure_code'], ['renderedSubject', 'rendered_subject'], ['renderedBody', 'rendered_body']]; + +const rendering_of = (body: Record): Record=>{ + const given = (v: unknown): boolean=>typeof v === 'string' || v === null; + const out: Record = Object.fromEntries(RENDERING_KEYS.filter(([from])=>given(body[from])).map(([from, to])=>[to, body[from]])); + const missing = body.missingVariables === null ? null : strings_of(body.missingVariables); + if (missing !== undefined) + { + out.missing_variables = missing; + } + return out; +}; + +// 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, and missing_variables is a list of names or null. +// Reply's code for the same failure: neither is read here. const direct_send_of = (a: Answer, kind: 'read' | 'write'): Record=>{ const body = expect_object(a, kind); if (typeof body.reference !== 'string' || body.reference === '' || typeof body.state !== 'string' || body.state === '') @@ -27,9 +42,7 @@ const direct_send_of = (a: Answer, kind: 'read' | 'write'): Record Date: Wed, 28 Oct 2026 17:31:50 -0700 Subject: [PATCH 15/24] fix: direct-send get and cancel refuse . and .. as a reference before any call Encoding leaves a dot as it is, and the URL parser reads a path segment of . or .. as a step up the path, so cancel .. would reach another route. Both are refused as usage.reference (exit 2); every other reference is still sent as given. --- README.md | 3 ++- src/__tests__/operations/direct-sends.test.ts | 14 +++++++++++++- src/operations/commands.ts | 3 ++- src/operations/direct-sends.ts | 9 ++++++++- 4 files changed, 25 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 916053a..34982b0 100644 --- a/README.md +++ b/README.md @@ -327,7 +327,8 @@ schedule list`). The answer then adds Reply's `reference`, `send_after` and `sta Reply gives it. `status: "sent"` means Reply took the send, and `state`, when present, says whether it has gone out: `queued` or `sending` is not yet, then `sent`, `failed` or `cancelled`. `reply direct-send get ` reads the send later, and `reply direct-send cancel ` stops -one that has not gone out; the reference is Reply's, passed on as given. An answer without `state` +one that has not gone out; the reference is Reply's, passed on as given, except that `.` and `..` +are refused (exit 2), since a path reads either as a step up. An answer without `state` comes from a Reply that does not know these flags yet: it sent at once, as without them. `--idempotency-key` goes to Reply as the `Idempotency-Key` header, never in the body. A Reply that diff --git a/src/__tests__/operations/direct-sends.test.ts b/src/__tests__/operations/direct-sends.test.ts index ec9ddcc..89ac721 100644 --- a/src/__tests__/operations/direct-sends.test.ts +++ b/src/__tests__/operations/direct-sends.test.ts @@ -83,7 +83,8 @@ describe('direct-send get', ()=>{ }); it('sends the reference as given, encoded into the path and never checked or parsed', async()=>{ - for (const [reference, path] of [['ds_8F2k', 'ds_8F2k'], ['a/b c?d', 'a%2Fb%20c%3Fd'], ['email-0', 'email-0']]) + for (const [reference, path] of [['ds_8F2k', 'ds_8F2k'], ['a/b c?d', 'a%2Fb%20c%3Fd'], ['email-0', 'email-0'], + ['a.b', 'a.b'], ['...', '...'], ['.a', '.a'], [' ..', '%20..']]) { mock_fetch.mockReset(); answer(json({...QUEUED, reference})); @@ -92,6 +93,17 @@ describe('direct-send get', ()=>{ } }); + it('refuses . and .. before any call: a path segment of either would be read as a step up the path, not as a reference', async()=>{ + for (const dots of ['.', '..']) + { + for (const fn of [handle_direct_send_get, handle_direct_send_cancel]) + { + expect(await failure(()=>fn(dots, ctx(), {})), `${fn.name} ${dots}`).toMatchObject({code: 'usage.reference', exit_code: 2}); + } + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); + it('refuses a blank reference before any call', async()=>{ for (const blank of ['', ' ']) { diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 9f989c3..014190e 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -575,7 +575,8 @@ const direct_send_command = new Command('direct-send').description('Read or canc const DIRECT_SEND = 'Result: {"reference","channel","contact_id","state","send_after","sent_at","message_id","failure_reason",\n' + '"cancelled_at"}, Reply\'s fields under these names, each null when Reply gives none. The reference is Reply\'s, from the\n' - + 'answer of a send made with --send-after; it is passed on as given and never read. state is Reply\'s own word: queued\n' + + 'answer of a send made with --send-after; it is passed on as given and never read, except that . and .. are refused\n' + + '(usage.reference, exit 2), since a path reads either as a step up. state is Reply\'s own word: queued\n' + 'or sending is not yet sent, then sent, failed or cancelled. failure_code, missing_variables, rendered_subject and\n' + 'rendered_body are added only when Reply gives them: failure_reason is a sentence for a person, never parsed;\n' + 'failure_code is Reply\'s code for the failure, the one to branch on. missing_variables lists the template variables\n' diff --git a/src/operations/direct-sends.ts b/src/operations/direct-sends.ts index 0f2ab1c..336d7d8 100644 --- a/src/operations/direct-sends.ts +++ b/src/operations/direct-sends.ts @@ -5,12 +5,19 @@ import {print_result} from './result'; import type {Op_globals} from './options'; import type {Cli_context} from '../context'; -// The reference is Reply's and opaque: it is sent as given, encoded into the path, and never read. +// The reference is Reply's and opaque: it is sent as given, encoded into the path, and never read +// beyond refusing what cannot name a send. const path_of = (reference: string): string=>{ if (reference.trim() === '') { throw new UsageError('No reference was given.', {code: 'usage.reference', hint: 'A send made with --send-after answers its reference.'}); } + // Encoding leaves a dot as it is, and a path segment of . or .. is read as a step up the path: the + // call would reach another route. + if (reference === '.' || reference === '..') + { + throw new UsageError(`${reference} is not a reference.`, {code: 'usage.reference', hint: 'A send made with --send-after answers its reference.'}); + } return `/v3/direct-sends/${encodeURIComponent(reference)}`; }; From 17a62924abf4981e70a21249a85c604b7c98f967 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 17:33:34 -0700 Subject: [PATCH 16/24] test: a 404 that is an HTML page or plain text stays reply.refused with no reply code A proxy in front of Reply can answer a route it does not know with a page that is not JSON. The sends, direct-send get and cancel, and the inbox feed each now hold that such a 404 is reply.refused with status 404 and no reply_code, as an empty one and a problem without a code are. --- src/__tests__/operations/direct-send.test.ts | 4 +++- src/__tests__/operations/direct-sends.test.ts | 4 +++- src/__tests__/operations/inbox-events.test.ts | 18 ++++++++++++++---- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index d90cff8..f35c838 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -714,10 +714,12 @@ describe('a send for later', ()=>{ expect((e as {hint?: string}).hint).toContain('may send it twice'); }); - it('a 404 with no code of Reply\'s own stays reply.refused, status 404 and no reply code, an empty body or a problem without one', async()=>{ + it('a 404 with no code of Reply\'s own stays reply.refused, status 404 and no reply code, an empty body, a problem without one, or a page that is not JSON', async()=>{ const bare: [string, ()=>Response][] = [ ['empty', ()=>new Response(null, {status: 404})], ['problem', ()=>json({title: 'Not Found', status: 404}, 404, {'Content-Type': 'application/problem+json'})], + ['html', ()=>new Response('Not Found', {status: 404, headers: {'Content-Type': 'text/html'}})], + ['text', ()=>new Response('Not Found', {status: 404, headers: {'Content-Type': 'text/plain'}})], ]; for (const [name, message, opts] of SENDS) { diff --git a/src/__tests__/operations/direct-sends.test.ts b/src/__tests__/operations/direct-sends.test.ts index 89ac721..1eaa0b6 100644 --- a/src/__tests__/operations/direct-sends.test.ts +++ b/src/__tests__/operations/direct-sends.test.ts @@ -17,10 +17,12 @@ const failure = (fn: () => Promise)=>fn().catch((x: unknown)=>x); const lost_connection = ()=>Object.assign(new TypeError('fetch failed'), {cause: Object.assign(new Error('ECONNRESET'), {code: 'ECONNRESET'})}); -// A 404 with no code of Reply's own: how a Reply without the route answers. +// A 404 with no code of Reply's own: how a Reply without the route, or a proxy in front of it, answers. const BARE_404: [string, ()=>Response][] = [ ['empty', ()=>new Response(null, {status: 404})], ['problem without a code', ()=>json({title: 'Not Found', status: 404}, 404, {'Content-Type': 'application/problem+json'})], + ['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'}})], ]; describe('direct-send get', ()=>{ diff --git a/src/__tests__/operations/inbox-events.test.ts b/src/__tests__/operations/inbox-events.test.ts index 93bda50..416d087 100644 --- a/src/__tests__/operations/inbox-events.test.ts +++ b/src/__tests__/operations/inbox-events.test.ts @@ -118,10 +118,20 @@ describe('inbox events', ()=>{ }); it('a 404 with no code of Reply\'s own, from a Reply without the feed, is reply.refused with status 404 and no reply code', async()=>{ - answer(new Response(null, {status: 404})); - const e = await failure({}); - expect(e).toMatchObject({code: 'reply.refused', status: 404}); - expect((e as {reply_code?: string}).reply_code).toBeUndefined(); + 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(); + answer(res()); + const e = await failure({}); + expect(e, label).toMatchObject({code: 'reply.refused', status: 404, exit_code: 1}); + expect((e as {reply_code?: string}).reply_code, label).toBeUndefined(); + } }); it('a page without its items, has_more or cursor cannot be read, and the read is safe to make again', async()=>{ From eb08c59b9b1830b7ab0586970f9f9c2f05a38443 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 17:35:28 -0700 Subject: [PATCH 17/24] fix: contact.missing_variables leaves the names out when Reply gives no list A refusal without Reply's list printed an empty one, which reads as Reply having said no variable was missing. The key is now left out, as the reused key's fields and the read of a send leave out what Reply does not give. --- README.md | 4 ++-- src/__tests__/operations/direct-send.test.ts | 16 ++++++++++++---- src/operations/commands.ts | 4 ++-- src/operations/direct-send.ts | 5 ++++- 4 files changed, 20 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 34982b0..1ca404d 100644 --- a/README.md +++ b/README.md @@ -312,8 +312,8 @@ variables, and refuses one it cannot fill with `linkedin.missing_variables`. it to. An email Reply sends within the request adds `rendered_subject` and `rendered_body`, the text as Reply filled it in, when Reply gives them; a send held for later has neither. A template variable Reply cannot fill is `contact.missing_variables`, with the names under the error's -`details.missing_variables`, and a template Reply cannot render is `contact.rendering_failed`, with -Reply's message as its `detail`. Neither sends anything: +`details.missing_variables` when Reply lists them, and a template Reply cannot render is +`contact.rendering_failed`, with Reply's message as its `detail`. Neither sends anything: ```sh # {"error":{"code":"contact.missing_variables",…,"details":{"missing_variables":["FirstName","Company"]}}} diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index f35c838..fb06766 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -813,10 +813,18 @@ describe('a direct email Reply renders', ()=>{ expect(e).toMatchObject({code: 'contact.missing_variables', status: 400, exit_code: 1, reply_code: 'contact.missingVariables', details: {missing_variables: ['FirstName', 'Company']}, ids: {contact_id: 456}}); expect((e as {to_json: () => unknown}).to_json()).toMatchObject({error: {details: {missing_variables: ['FirstName', 'Company']}}}); - mock_fetch.mockReset(); - answer(json({code: 'contact.missingVariables', detail: 'The message has variables with no value.'}, 400)); - expect(await failure('send-email', EMAIL, EMAIL_OPTS)).toMatchObject({code: 'contact.missing_variables', - details: {missing_variables: []}}); + }); + + it('leaves missing_variables out when Reply gives no list of names, as the reused key leaves its fields out', async()=>{ + for (const missing of [undefined, null, 'FirstName', ['FirstName', 7]]) + { + mock_fetch.mockReset(); + answer(json({code: 'contact.missingVariables', detail: 'The message has variables with no value.', missingVariables: missing}, 400)); + const e = await failure('send-email', EMAIL, EMAIL_OPTS); + expect(e, JSON.stringify(missing)).toMatchObject({code: 'contact.missing_variables', status: 400, exit_code: 1}); + expect((e as {details?: unknown}).details, JSON.stringify(missing)).toBeUndefined(); + expect((e as {to_json: () => {error: object}}).to_json().error, JSON.stringify(missing)).not.toHaveProperty('details'); + } }); it('maps a template Reply could not render to contact.rendering_failed, with Reply\'s message as the detail', async()=>{ diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 014190e..3da8ce4 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -337,8 +337,8 @@ later_options(add_contact_options(contact_command.command('send-email'), true) + 'Reply tracks neither links nor opens unless --track-links or --track-opens asks it to. An email sent within the\n' + 'request adds rendered_subject and rendered_body, the subject and body as Reply filled them in, when Reply gives\n' + 'them; a send held for later has neither. contact.missing_variables names the variables Reply could not fill in\n' - + 'details.missing_variables, and contact.rendering_failed is a template Reply could not render, its message in\n' - + 'detail. Neither sends anything.\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 + SENT_TO('email', 'email'), SEND_TWICE('email'))) .action(run(async(cmd)=>{ diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index afaafe1..22cec19 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -110,7 +110,10 @@ const strings_of = (v: unknown): string[] | undefined=> const REFUSALS: Record = { 'contact.missingVariables': { status: 400, code: 'contact.missing_variables', title: 'The email holds a template variable Reply could not fill, so nothing was sent.', - details: body=>({missing_variables: strings_of(body.missingVariables) ?? []}), + details: body=>{ + const missing = strings_of(body.missingVariables); + return missing === undefined ? undefined : {missing_variables: missing}; + }, }, 'contact.renderingFailed': { status: 400, code: 'contact.rendering_failed', title: 'Reply could not render the email\'s template, so nothing was sent.', From 1df24c6742582cccfe32b350616a9a5f6dff7a84 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 17:36:33 -0700 Subject: [PATCH 18/24] fix: the two template refusals are read only from send-email's answer contact.missingVariables and contact.renderingFailed sat in the table all five sends share, so a LinkedIn send answering either would have been named an email's refusal. They now sit in a table kept per channel, as the idempotency key's codes do, and a LinkedIn send falls to the usual mapping. --- src/__tests__/operations/direct-send.test.ts | 16 ++++++++++ src/operations/direct-send.ts | 31 +++++++++++++------- 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index fb06766..ab5ac31 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -847,6 +847,22 @@ describe('a direct email Reply renders', ()=>{ } }); + it('reads the two codes only from the email route: a LinkedIn send answering either falls to the usual mapping', async()=>{ + const sends: [Direct_send_name, unknown][] = [['linkedin-connect', {note: NOTE}], ['linkedin-message', {body: TEXT}], + ['linkedin-inmail', {subject: SUBJECT, body: TEXT}], ['linkedin-voice', {script: SCRIPT}]]; + for (const [name, message] of sends) + { + for (const reply_code of ['contact.missingVariables', 'contact.renderingFailed']) + { + mock_fetch.mockReset(); + answer(json({code: reply_code, missingVariables: ['FirstName']}, 400)); + const e = await failure(name, message, LINKEDIN_OPTS); + expect(e, `${name} ${reply_code}`).toMatchObject({code: 'reply.refused', status: 400, reply_code, exit_code: 1}); + expect((e as {details?: unknown}).details, `${name} ${reply_code}`).toBeUndefined(); + } + } + }); + it('sends trackLinks and trackOpens only when their flags are given, and nothing of them otherwise', async()=>{ const cases: [Direct_send_opts, Record][] = [ [EMAIL_OPTS, {}], diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index 22cec19..d3e69bc 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -106,18 +106,26 @@ const picked = (keys: [string, string][], from: Record): Record const strings_of = (v: unknown): string[] | undefined=> Array.isArray(v) && v.every(s=>typeof s === 'string') ? v : undefined; -// Reply's refusals of a direct send, by status and code. Each one is definite: nothing was sent. -const REFUSALS: Record = { - 'contact.missingVariables': { - status: 400, code: 'contact.missing_variables', title: 'The email holds a template variable Reply could not fill, so nothing was sent.', - details: body=>{ - const missing = strings_of(body.missingVariables); - return missing === undefined ? undefined : {missing_variables: missing}; +// The email route's refusals of the template it renders. Only that route renders one, so a LinkedIn +// send answering either code falls to the usual mapping. Each one is definite: nothing was sent. +const TEMPLATE_REFUSALS: Record> = { + email: { + 'contact.missingVariables': { + status: 400, code: 'contact.missing_variables', title: 'The email holds a template variable Reply could not fill, so nothing was sent.', + details: body=>{ + const missing = strings_of(body.missingVariables); + return missing === undefined ? undefined : {missing_variables: missing}; + }, + }, + 'contact.renderingFailed': { + status: 400, code: 'contact.rendering_failed', title: 'Reply could not render the email\'s template, so nothing was sent.', }, }, - 'contact.renderingFailed': { - status: 400, code: 'contact.rendering_failed', title: 'Reply could not render the email\'s template, so nothing was sent.', - }, + linkedin: {}, +}; + +// Reply's refusals of a direct send, by status and code. Each one is definite: nothing was sent. +const REFUSALS: Record = { 'contact.emailAccountNotFound': { status: 400, code: 'email_account.not_found', title: 'Reply has no mailbox by that id that this account can send from, so nothing was sent.', }, @@ -232,7 +240,8 @@ const send_refusal = (a: Answer, contact_id: number, by: Channel): Operation_err retry_after: parse_retry_after(a.headers['retry-after']) ?? undefined, details: {limit: LIMITS[reply_code]}, }); } - return known_refusal(a, REFUSALS) ?? known_refusal(a, KEY_REFUSALS[by]) ?? refusal(a, 'write'); + return known_refusal(a, REFUSALS) ?? known_refusal(a, TEMPLATE_REFUSALS[by]) ?? known_refusal(a, KEY_REFUSALS[by]) + ?? refusal(a, 'write'); }; const positive_integer = (v: unknown): number | null=> From d374a907accaa0ce83895786b41579ae4dd0387d Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 17:37:55 -0700 Subject: [PATCH 19/24] docs: a repeat of a send given a person's fields answers contact.already_held first The help and the README said a repeat with the same key answers with the send the key first made. A send given a person's fields finds the contact the first one created before the key is read, so its repeat answers contact.already_held, which is safe as well: nothing is sent twice. --- README.md | 6 ++++-- src/__tests__/operations/commands.test.ts | 3 +++ src/operations/commands.ts | 5 +++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 1ca404d..6118fa3 100644 --- a/README.md +++ b/README.md @@ -334,8 +334,10 @@ comes from a Reply that does not know these flags yet: it sent at once, as witho `--idempotency-key` goes to Reply as the `Idempotency-Key` header, never in the body. A Reply that knows the header answers a repeat with the same key with the send the key first made; while that one is still being made the answer is `idempotency_key.in_use`, and the same key on a different -send is `idempotency_key.reused`. Neither sends anything. `idempotency_key.reused` names the send -the key was first taken for under the error's `details`: its `reference`, `state` and `send_after`, +send is `idempotency_key.reused`. Neither sends anything. A repeat of a send given a person's +fields (`--contact -`) answers `contact.already_held` first, since the first one created the +contact: that is safe too, as nothing is sent twice. `idempotency_key.reused` names the send the +key was first taken for under the error's `details`: its `reference`, `state` and `send_after`, each only when Reply gives it. A key is 1 to 255 printable ASCII characters; a space inside is kept, and one at either end is refused (`usage.idempotency_key`), since a header loses it on the way out. diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index 82e8a6c..ab29fc2 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -290,6 +290,9 @@ describe('operations/commands', ()=>{ expect(flat, text).toContain('--idempotency-key goes as the Idempotency-Key header'); expect(flat, text).toContain('A Reply that knows the header answers a repeat with the same key with the send the key first made; while that one is still ' + 'being made the answer is idempotency_key.in_use, and the same key on a different send is idempotency_key.reused'); + // Given a person's fields, a repeat finds the contact the first one created before it reaches the key. + expect(flat, text).toContain('A repeat of a send given a person\'s fields answers contact.already_held first, since the ' + + 'first one created the contact: that is safe too, as nothing is sent twice'); expect(flat, text).toContain('idempotency_key.reused names the send the key was first taken for in details: reference, ' + 'state and send_after, each only when Reply gives it'); // Exactly the codes its endpoint publishes, then the shared ones, as the help lists them. diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 3da8ce4..256da8a 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -306,8 +306,9 @@ const LATER = 'With --send-after Reply holds the send until that moment, given w + 'without them. --idempotency-key goes as the Idempotency-Key header, never in the body. A Reply that knows the header\n' + 'answers a repeat with the same key with the send the key first made; while that one is still being made the answer\n' + 'is idempotency_key.in_use, and the same key on a different send is idempotency_key.reused. Neither sends anything.\n' - + 'idempotency_key.reused names the send the key was first taken for in details: reference, state and send_after, each\n' - + 'only when Reply gives it.\n'; + + 'A repeat of a send given a person\'s fields answers contact.already_held first, since the first one created the\n' + + 'contact: that is safe too, as nothing is sent twice. idempotency_key.reused names the send the key was first taken\n' + + 'for in details: reference, state and send_after, each only when Reply gives it.\n'; // The refusals of a send's key, the same on every direct send, after each send's own. const KEY_CODES = ['idempotency_key.in_use', 'idempotency_key.reused']; From e54feb4fc4cce771bc9ab9e33bca92f6a8f91e23 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 17:42:20 -0700 Subject: [PATCH 20/24] feat: the inbox feed is reply inbox changes, read from GET /v3/inbox/threads/changes The feed names which threads changed, not what happened in them, so Reply names the route threads/changes and its window code inboxThread.changeWindowExpired. The command follows as inbox changes, with the same flags, the same page and the same two CLI codes. Nothing has shipped under the old name, so there is no alias. --- README.md | 8 ++--- src/__tests__/operations/commands.test.ts | 9 ++++-- ...x-events.test.ts => inbox-changes.test.ts} | 30 +++++++++---------- src/__tests__/operations/program.test.ts | 12 ++++---- src/operations/commands.ts | 8 ++--- src/operations/inbox.ts | 10 +++---- 6 files changed, 40 insertions(+), 37 deletions(-) rename src/__tests__/operations/{inbox-events.test.ts => inbox-changes.test.ts} (87%) diff --git a/README.md b/README.md index 6118fa3..dc20f89 100644 --- a/README.md +++ b/README.md @@ -205,7 +205,7 @@ prints JSON (indented; compact with `--json`) and says what happened in a stable | `reply direct-send get ` | a send as Reply holds it: whether it has gone out, when, and why it failed | | `reply direct-send cancel ` | stop a send that has not gone out yet → `state` `cancelled` | | `reply inbox list (--contact-id \| --sequence-id) [--source] [--channel] [--category-id] [--since]` | one page of threads | -| `reply inbox events [--cursor … \| --since …] [--top N]` | one page of the inbox feed, read forward by cursor | +| `reply inbox changes [--cursor … \| --since …] [--top N]` | one page of the inbox feed, read forward by cursor | | `reply inbox get ` | a thread with its subject, and one page of its messages | | `reply inbox reply --message -` | reply in the thread, on its own channel → `sent` | | `reply inbox categories` | the categories a thread can be filed under | @@ -356,7 +356,7 @@ added only when Reply gives them. `failure_reason` is a sentence for a person an again. A send already gone out or failed is `direct_send.already_sent` or `direct_send.already_failed`, and a reference Reply has no send for is `direct_send.not_found`. -`reply inbox events` reads the inbox feed forward. Each page holds the threads whose latest message, +`reply inbox changes` reads the inbox feed forward. Each page holds the threads whose latest message, inbound or outbound, changed, oldest first and as Reply gives them, with `has_more` and a `cursor`. Start with `--since ` (inclusive, at most 30 days ago) or with neither flag, which reads the last 30 days, then pass the answered cursor back with `--cursor` while `has_more` is true. Loop on @@ -367,10 +367,10 @@ otherwise, unreadable or ahead of its clock, is `inbox.cursor_refused`, with `cu `details.fields`; start again the same way. ```sh -reply inbox events --since 2026-11-01T00:00:00Z --json +reply inbox changes --since 2026-11-01T00:00:00Z --json # {"items":[{"threadId":9876,"contactId":456,"channel":"email","lastActivityDate":"2026-11-03T14:02:11Z",…}], # "has_more":true,"cursor":"AQjfObhYHZgAAADjVg"} -reply inbox events --cursor AQjfObhYHZgAAADjVg --json +reply inbox changes --cursor AQjfObhYHZgAAADjVg --json ``` A Reply that does not have `direct-send get`, `direct-send cancel` or the feed yet answers diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index ab29fc2..c0533f2 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -24,7 +24,7 @@ describe('operations/commands', ()=>{ expect(contact_list_command.commands.map(c=>c.name())).toEqual(['add-contact']); expect(contact_command.commands.map(c=>c.name())).toEqual(['find', 'get', 'update', 'delete', 'opt-out', 'send-email', 'linkedin-connect', 'linkedin-message', 'linkedin-inmail', 'linkedin-voice']); - expect(inbox_command.commands.map(c=>c.name())).toEqual(['list', 'events', 'get', 'reply', 'categories', 'categorize', 'mark-read', 'mark-unread']); + expect(inbox_command.commands.map(c=>c.name())).toEqual(['list', 'changes', 'get', 'reply', 'categories', 'categorize', 'mark-read', 'mark-unread']); expect(account_command.commands.map(c=>c.name())).toEqual(['list']); expect(schedule_command.commands.map(c=>c.name())).toEqual(['list']); expect(direct_send_command.commands.map(c=>c.name())).toEqual(['get', 'cancel']); @@ -166,8 +166,8 @@ describe('operations/commands', ()=>{ expect(flags(sub(contact_command, 'delete'))).toEqual([]); }); - it('inbox events takes --cursor, --since and --top, and says how the feed is read forward', ()=>{ - const c = sub(inbox_command, 'events'); + it('inbox changes takes --cursor, --since and --top, and says how the feed is read forward', ()=>{ + const c = sub(inbox_command, 'changes'); expect(flags(c)).toEqual(['--cursor', '--since', '--top']); expect(c.registeredArguments).toEqual([]); const text = help_of(c); @@ -181,6 +181,9 @@ describe('operations/commands', ()=>{ expect(flat, text).toContain('A cursor Reply will not read otherwise, unreadable or ahead of its clock, is inbox.cursor_refused'); expect(text, text).toContain(' inbox.cursor_expired\n inbox.cursor_refused\n'); expect(text, text).not.toContain('outcome.unknown'); + // The feed names the threads that changed, and its examples use the command's own name. + expect(text, text).toContain('inbox changes --since 2026-11-01T00:00:00Z'); + expect(text, text).not.toContain('events'); }); it('sequence list and create take the name only through --name -, and create says a repeat may make a second one', ()=>{ diff --git a/src/__tests__/operations/inbox-events.test.ts b/src/__tests__/operations/inbox-changes.test.ts similarity index 87% rename from src/__tests__/operations/inbox-events.test.ts rename to src/__tests__/operations/inbox-changes.test.ts index 416d087..de93b83 100644 --- a/src/__tests__/operations/inbox-events.test.ts +++ b/src/__tests__/operations/inbox-changes.test.ts @@ -1,10 +1,10 @@ import {describe, it, expect, beforeEach} from 'vitest'; import {mock_fetch, json, ctx, sent, answer, capture} from './helpers'; -import {handle_inbox_events} from '../../operations/inbox'; +import {handle_inbox_changes} from '../../operations/inbox'; beforeEach(()=>{ mock_fetch.mockReset(); }); -const EVENT = { +const CHANGE = { threadId: 9876, contactId: 456, channel: 'email', lastActivityDate: '2026-11-03T14:02:11Z', sequenceId: 12, category: 'interested', hasMeetingIntent: false, newFieldReplyAdds: 'kept', flags: {hasReply: true, hasBounce: false, hasAutoReply: false, hasOutOfOffice: false}, @@ -12,12 +12,12 @@ const EVENT = { }; type Opts = {cursor?: string; since?: string; top?: string}; -const events = async(opts: Opts = {})=>JSON.parse((await capture(()=>handle_inbox_events(opts, ctx(), {json: true}))).out); -const failure = (opts: Opts)=>handle_inbox_events(opts, ctx(), {}).catch((x: unknown)=>x); +const changes = async(opts: Opts = {})=>JSON.parse((await capture(()=>handle_inbox_changes(opts, ctx(), {json: true}))).out); +const failure = (opts: Opts)=>handle_inbox_changes(opts, ctx(), {}).catch((x: unknown)=>x); // A cursor or a since older than the feed's 30 days: a business problem with a code of its own. const WINDOW_EXPIRED = { - code: 'inboxThread.eventWindowExpired', title: 'Event window expired', status: 400, + code: 'inboxThread.changeWindowExpired', title: 'Change window expired', status: 400, detail: 'The feed keeps 30 days. Start again with \'since\' (at most 30 days ago) or with no parameters, which reads the last 30 days.', }; // How Reply's API document publishes a cursor it will not read: a validation problem with no code, pointing at /cursor. @@ -27,16 +27,16 @@ const CURSOR_UNREADABLE = { }; const problem = (body: unknown, status: number)=>json(body, status, {'Content-Type': 'application/problem+json'}); -describe('inbox events', ()=>{ +describe('inbox changes', ()=>{ it('reads one page of the feed and passes the items on as Reply gives them, under has_more and cursor', async()=>{ - answer(json({items: [EVENT], hasMore: true, cursor: 'AQjfObhYHZgAAADjVg'})); - expect(await events()).toStrictEqual({items: [EVENT], has_more: true, cursor: 'AQjfObhYHZgAAADjVg'}); - expect(sent()).toEqual([{method: 'GET', url: 'https://api/v3/inbox/events', body: undefined}]); + answer(json({items: [CHANGE], hasMore: true, cursor: 'AQjfObhYHZgAAADjVg'})); + expect(await changes()).toStrictEqual({items: [CHANGE], has_more: true, cursor: 'AQjfObhYHZgAAADjVg'}); + expect(sent()).toEqual([{method: 'GET', url: 'https://api/v3/inbox/threads/changes', body: undefined}]); }); it('an empty page keeps the cursor Reply gives with it, so the next read goes on from there', async()=>{ answer(json({items: [], hasMore: false, cursor: 'AQjfObkJcH4Af____w'})); - expect(await events({cursor: 'AQjfObhYHZgAAADjVg'})).toStrictEqual({items: [], has_more: false, cursor: 'AQjfObkJcH4Af____w'}); + expect(await changes({cursor: 'AQjfObhYHZgAAADjVg'})).toStrictEqual({items: [], has_more: false, cursor: 'AQjfObkJcH4Af____w'}); }); it('sends the cursor as given and encoded, --since in UTC and not shifted, and --top only when given', async()=>{ @@ -50,8 +50,8 @@ describe('inbox events', ()=>{ { mock_fetch.mockReset(); answer(json({items: [], hasMore: false, cursor: 'c'})); - await events(opts); - expect(sent()[0].url, query).toBe(`https://api/v3/inbox/events?${query}`); + await changes(opts); + expect(sent()[0].url, query).toBe(`https://api/v3/inbox/threads/changes?${query}`); } }); @@ -78,14 +78,14 @@ describe('inbox events', ()=>{ answer(problem(WINDOW_EXPIRED, 400)); const e = await failure(opts); expect(e, JSON.stringify(opts)).toMatchObject({code: 'inbox.cursor_expired', status: 400, exit_code: 1, - reply_code: 'inboxThread.eventWindowExpired', detail: WINDOW_EXPIRED.detail}); + reply_code: 'inboxThread.changeWindowExpired', detail: WINDOW_EXPIRED.detail}); expect((e as {hint?: string}).hint, JSON.stringify(opts)).toContain('--since'); } }); it('the window\'s code under another status is not the window: it maps as everywhere else', async()=>{ answer(problem({...WINDOW_EXPIRED, status: 409}, 409)); - expect(await failure({cursor: 'c'})).toMatchObject({code: 'reply.refused', reply_code: 'inboxThread.eventWindowExpired'}); + expect(await failure({cursor: 'c'})).toMatchObject({code: 'reply.refused', reply_code: 'inboxThread.changeWindowExpired'}); }); it('a cursor Reply will not read is inbox.cursor_refused, with the same hint as the expired window', async()=>{ @@ -136,7 +136,7 @@ describe('inbox events', ()=>{ it('a page without its items, has_more or cursor cannot be read, and the read is safe to make again', async()=>{ for (const body of [{items: [], hasMore: false}, {items: [], cursor: 'c'}, {items: {}, hasMore: false, cursor: 'c'}, - {items: [], hasMore: 'no', cursor: 'c'}, {items: [], hasMore: false, cursor: 7}, [EVENT]]) + {items: [], hasMore: 'no', cursor: 'c'}, {items: [], hasMore: false, cursor: 7}, [CHANGE]]) { mock_fetch.mockReset(); answer(json(body)); diff --git a/src/__tests__/operations/program.test.ts b/src/__tests__/operations/program.test.ts index b9590b4..8006a89 100644 --- a/src/__tests__/operations/program.test.ts +++ b/src/__tests__/operations/program.test.ts @@ -225,16 +225,16 @@ describe('the program', ()=>{ expect([init.method, url]).toEqual(['POST', 'https://api.reply.io/v3/direct-sends/email-1001/cancel']); }); - it('inbox events reads its flags through commander: both --cursor and --since exit 2, an expired cursor exits 1 with its code', async()=>{ - const both = await run_program(['--json', '-q', '-k', 'key-1', 'inbox', 'events', '--cursor', 'c1', '--since', '2026-11-03T14:00:00Z']); + it('inbox changes reads its flags through commander: both --cursor and --since exit 2, an expired cursor exits 1 with its code', async()=>{ + const both = await run_program(['--json', '-q', '-k', 'key-1', 'inbox', 'changes', '--cursor', 'c1', '--since', '2026-11-03T14:00:00Z']); expect(both.code).toBe(2); expect(mock_fetch).not.toHaveBeenCalled(); - answer(json({code: 'inboxThread.eventWindowExpired', status: 400, detail: 'The feed keeps 30 days.'}, 400, + answer(json({code: 'inboxThread.changeWindowExpired', status: 400, detail: 'The feed keeps 30 days.'}, 400, {'Content-Type': 'application/problem+json'})); - const {code, err} = await run_program(['--json', '-q', '-k', 'key-1', 'inbox', 'events', '--cursor', 'c1', '--top', '50']); + const {code, err} = await run_program(['--json', '-q', '-k', 'key-1', 'inbox', 'changes', '--cursor', 'c1', '--top', '50']); expect(code).toBe(1); - expect(JSON.parse(err)).toMatchObject({error: {code: 'inbox.cursor_expired', status: 400, reply_code: 'inboxThread.eventWindowExpired'}}); - expect((mock_fetch.mock.calls[0] as [string, RequestInit])[0]).toBe('https://api.reply.io/v3/inbox/events?cursor=c1&top=50'); + expect(JSON.parse(err)).toMatchObject({error: {code: 'inbox.cursor_expired', status: 400, reply_code: 'inboxThread.changeWindowExpired'}}); + expect((mock_fetch.mock.calls[0] as [string, RequestInit])[0]).toBe('https://api.reply.io/v3/inbox/threads/changes?cursor=c1&top=50'); }); it('a usage error exits 2 before any request', async()=>{ diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 256da8a..1279933 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -8,7 +8,7 @@ import {handle_sequence_list, handle_sequence_create} from './sequence-by-name'; import {handle_sequence_add_contact, handle_sequence_remove_contact} from './sequence-membership'; import {handle_sequence_pause, handle_sequence_start} from './sequence-state'; import { - handle_inbox_list, handle_inbox_events, handle_inbox_get, handle_inbox_categories, handle_inbox_categorize, handle_inbox_mark_read, handle_inbox_mark_unread, + handle_inbox_list, handle_inbox_changes, handle_inbox_get, handle_inbox_categories, handle_inbox_categorize, handle_inbox_mark_read, handle_inbox_mark_unread, } from './inbox'; import {handle_inbox_reply} from './inbox-reply'; import {handle_contact_list_add_contact} from './contact-list'; @@ -438,12 +438,12 @@ inbox_command.command('list') await handle_inbox_list(cmd.opts(), ctx, g); })); -inbox_command.command('events') +inbox_command.command('changes') .option('--cursor ', 'Go on from the cursor a previous page answered, passed back unchanged') .option('--since ', 'Start at this moment, inclusive, given with its offset; at most 30 days ago') .option('--top ', 'Items per page, 1-1000 (default: Reply\'s)') .description('One page of the inbox feed: each thread whose latest message changed, oldest first, read forward by cursor') - .addHelpText('after', help([ex('inbox events --since 2026-11-01T00:00:00Z'), ex('inbox events --cursor AQjfObhYHZgAAADjVg --top 200')], + .addHelpText('after', help([ex('inbox changes --since 2026-11-01T00:00:00Z'), ex('inbox changes --cursor AQjfObhYHZgAAADjVg --top 200')], ['inbox.cursor_expired', 'inbox.cursor_refused'], false, 'Result: {"items","has_more","cursor"}, the items as Reply gives them, one per thread whose latest message, inbound\n' + 'or outbound, changed: threadId, contactId, channel, lastActivityDate, flags (hasReply, hasBounce, hasAutoReply,\n' @@ -456,7 +456,7 @@ inbox_command.command('events') + 'A Reply without the feed answers reply.refused with status 404 and no reply_code.\n')) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); - await handle_inbox_events(cmd.opts(), ctx, g); + await handle_inbox_changes(cmd.opts(), ctx, g); })); inbox_command.command('get') diff --git a/src/operations/inbox.ts b/src/operations/inbox.ts index dce533f..962d7e1 100644 --- a/src/operations/inbox.ts +++ b/src/operations/inbox.ts @@ -66,13 +66,13 @@ const handle_inbox_list = async(opts: Inbox_list_opts, ctx: Cli_context, g: Op_g print_result({items: page.items, has_more: page.has_more}, g); }; -type Inbox_events_opts = {cursor?: string; since?: string; top?: string}; +type Inbox_changes_opts = {cursor?: string; since?: string; top?: string}; const START_AGAIN = 'Start again with --since (at most 30 days ago), or with neither flag to read the last 30 days.'; // The feed keeps 30 days. Reply refuses a cursor or a since older than that under a code of its own. const window_expired = (a: Answer): Operation_error | undefined=> - a.status === 400 && reply_code_of(a) === 'inboxThread.eventWindowExpired' + a.status === 400 && reply_code_of(a) === 'inboxThread.changeWindowExpired' ? new Operation_error('inbox.cursor_expired', 'Reply keeps the feed for 30 days, and the cursor or --since reaches further back.', { status: a.status, reply_code: reply_code_of(a), detail: detail_of(a), hint: START_AGAIN, }) @@ -85,7 +85,7 @@ const cursor_refused = (a: Answer, fields: string[]): Operation_error=> status: a.status, detail: detail_of(a), details: {fields}, hint: START_AGAIN, }); -const handle_inbox_events = async(opts: Inbox_events_opts, ctx: Cli_context, g: Op_globals): Promise=>{ +const handle_inbox_changes = async(opts: Inbox_changes_opts, ctx: Cli_context, g: Op_globals): Promise=>{ if (opts.cursor !== undefined && opts.since !== undefined) { throw new UsageError('Give --cursor or --since, not both.', {code: 'usage.inbox'}); @@ -111,7 +111,7 @@ const handle_inbox_events = async(opts: Inbox_events_opts, ctx: Cli_context, g: } const s = await open_session(ctx, g); const q = query.toString(); - const a = await call_reply(s, 'GET', q === '' ? '/v3/inbox/events' : `/v3/inbox/events?${q}`, 'read'); + const a = await call_reply(s, 'GET', q === '' ? '/v3/inbox/threads/changes' : `/v3/inbox/threads/changes?${q}`, 'read'); if (a.status !== 200) { const fields = opts.cursor !== undefined && a.status === 400 && reply_code_of(a) === undefined ? invalid_fields(a) : undefined; @@ -275,7 +275,7 @@ const handle_inbox_mark_unread = (thread_arg: string, ctx: Cli_context, g: Op_gl mark_thread(thread_arg, false, ctx, g); export { - handle_inbox_list, handle_inbox_events, handle_inbox_get, handle_inbox_categories, handle_inbox_categorize, + handle_inbox_list, handle_inbox_changes, handle_inbox_get, handle_inbox_categories, handle_inbox_categorize, handle_inbox_mark_read, handle_inbox_mark_unread, thread_not_found, SOURCES, CHANNELS, }; export type {Channel}; From 72e4f857d2554eea2ae2a2ad9042940b85d338f0 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 17:56:10 -0700 Subject: [PATCH 21/24] feat: every refused direct send names the send Reply holds, not only a reused key Reply now answers an email that fails after its row exists with its refusal plus reference, state and sendAfter, and replays that answer under the key. Each one given as a string goes under the error's details, beside the refusal's own such as missing_variables, through one helper for all five sends. The refusal's code and class are unchanged, and without the fields there is no details. --- README.md | 7 +- src/__tests__/operations/commands.test.ts | 2 + src/__tests__/operations/direct-send.test.ts | 79 +++++++++++++++++++- src/operations/commands.ts | 3 +- src/operations/direct-send.ts | 23 ++++-- 5 files changed, 102 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index dc20f89..6295391 100644 --- a/README.md +++ b/README.md @@ -338,8 +338,11 @@ send is `idempotency_key.reused`. Neither sends anything. A repeat of a send giv fields (`--contact -`) answers `contact.already_held` first, since the first one created the contact: that is safe too, as nothing is sent twice. `idempotency_key.reused` names the send the key was first taken for under the error's `details`: its `reference`, `state` and `send_after`, -each only when Reply gives it. A key is 1 to 255 printable ASCII characters; a space inside is kept, -and one at either end is refused (`usage.idempotency_key`), since a header loses it on the way out. +each only when Reply gives it. Any other refusal of a send Reply already holds, an email that +failed after Reply made its row for example, names that send the same way, beside the refusal's +own details such as `missing_variables`; its code is the refusal's own. A key is 1 to 255 +printable ASCII characters; a space inside is kept, and one at either end is refused +(`usage.idempotency_key`), since a header loses it on the way out. ```sh echo '{"body":"Following up on my note."}' | reply contact linkedin-message --contact-id 456 --linkedin-account-id 34 --message - --send-after 2026-11-03T14:00:00Z --idempotency-key follow-up-456-1 diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index c0533f2..3155318 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -298,6 +298,8 @@ describe('operations/commands', ()=>{ + 'first one created the contact: that is safe too, as nothing is sent twice'); expect(flat, text).toContain('idempotency_key.reused names the send the key was first taken for in details: reference, ' + 'state and send_after, each only when Reply gives it'); + expect(flat, text).toContain('Any other refusal of a send Reply already holds names that send the same way, beside the ' + + 'refusal\'s own details; its code is the refusal\'s own'); // Exactly the codes its endpoint publishes, then the shared ones, as the help lists them. const listed = text.split('\nErrors')[1].split('\nExit codes')[0].split('\n').slice(1).map(l=>l.trim()); expect(listed, name).toEqual([...codes, 'idempotency_key.in_use', 'idempotency_key.reused', 'access.denied', 'access.feature_unavailable', 'rate_limited', 'reply.unavailable', diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index ab5ac31..d889974 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -777,15 +777,20 @@ describe('a send made with an idempotency key', ()=>{ .toStrictEqual({reference: 'email-1001'}); }); - it('a reused key without the send, and a key in use, carry no details: the output is what it was', async()=>{ + it('a reused key or a key in use without the send carries no details: the output is what it was', async()=>{ for (const reply_code of ['contact.idempotencyKeyReused', 'contact.idempotencyKeyInUse']) { mock_fetch.mockReset(); - answer(json({code: reply_code, detail: 'Conflict.', reference: reply_code.endsWith('InUse') ? 'email-1001' : undefined}, 409)); + answer(json({code: reply_code, detail: 'Conflict.'}, 409)); const e = await failure('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...KEY}); expect((e as {details?: unknown}).details, reply_code).toBeUndefined(); expect(JSON.stringify((e as {to_json: () => unknown}).to_json()), reply_code).not.toContain('details'); } + // A key in use names the send too when Reply gives it, as every refusal of a send does. + mock_fetch.mockReset(); + answer(json({code: 'contact.idempotencyKeyInUse', detail: 'Conflict.', reference: 'email-1001'}, 409)); + expect((await failure('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...KEY}) as {details?: unknown}).details) + .toStrictEqual({reference: 'email-1001'}); }); it('reads those codes only under 409 and only in the send route\'s own family; any other answer is mapped as before', async()=>{ @@ -882,3 +887,73 @@ describe('a direct email Reply renders', ()=>{ } }); }); + +describe('a refused send that Reply holds a row for', ()=>{ + const EMAIL: unknown = {subject: SUBJECT, body: BODY}; + const HELD = {reference: 'email-1001', state: 'failed', sendAfter: '2026-11-03T14:00:00Z'}; + const details_of = (e: unknown): unknown=>(e as {details?: unknown}).details; + + it('names the send under details, reference, state and send_after, beside the refusal\'s code and class as before', async()=>{ + answer(json({code: 'contact.renderingFailed', detail: 'Unclosed block at line 2.', ...HELD}, 400)); + const e = await failure('send-email', EMAIL, EMAIL_OPTS); + expect(e).toMatchObject({code: 'contact.rendering_failed', status: 400, exit_code: 1, reply_code: 'contact.renderingFailed', + ids: {contact_id: 456}}); + expect(details_of(e)).toStrictEqual({reference: 'email-1001', state: 'failed', send_after: '2026-11-03T14:00:00Z'}); + expect((e as {to_json: () => unknown}).to_json()).toMatchObject({error: {details: {reference: 'email-1001', state: 'failed'}}}); + }); + + it('gives each field only when Reply gives it as a string', async()=>{ + const cases: [Record, unknown][] = [ + [{reference: 'email-1001'}, {reference: 'email-1001'}], + [{reference: 'email-1001', state: 7, sendAfter: null}, {reference: 'email-1001'}], + [{state: {failed: true}, sendAfter: ['2026-11-03T14:00:00Z']}, undefined], + ]; + for (const [held, details] of cases) + { + mock_fetch.mockReset(); + answer(json({code: 'contact.contactInBlackList', ...held}, 400)); + const e = await failure('send-email', EMAIL, EMAIL_OPTS); + expect(e, JSON.stringify(held)).toMatchObject({code: 'contact.blacklisted', exit_code: 1}); + expect(details_of(e), JSON.stringify(held)).toStrictEqual(details); + } + }); + + it('names it on a LinkedIn send\'s refusal too, a known code or one mapped as everywhere else', async()=>{ + const cases: [Direct_send_name, unknown, Response, string][] = [ + ['linkedin-message', {body: TEXT}, json({code: 'directLinkedIn.notConnected', ...HELD, reference: 'linkedin-1042'}, 409), + 'linkedin.not_connected'], + ['linkedin-connect', {note: NOTE}, json({code: 'directLinkedIn.somethingNew', ...HELD, reference: 'linkedin-1042'}, 400), + 'reply.refused'], + ]; + for (const [name, message, res, code] of cases) + { + mock_fetch.mockReset(); + answer(res); + const e = await failure(name, message, LINKEDIN_OPTS); + expect(e, name).toMatchObject({code, exit_code: 1}); + expect(details_of(e), name).toStrictEqual({reference: 'linkedin-1042', state: 'failed', send_after: '2026-11-03T14:00:00Z'}); + } + }); + + it('sits beside the details a refusal carries of its own: the unfilled names, a LinkedIn limit', async()=>{ + answer(json({code: 'contact.missingVariables', missingVariables: ['FirstName'], ...HELD}, 400)); + expect(details_of(await failure('send-email', EMAIL, EMAIL_OPTS))).toStrictEqual({missing_variables: ['FirstName'], + reference: 'email-1001', state: 'failed', send_after: '2026-11-03T14:00:00Z'}); + mock_fetch.mockReset(); + answer(json({code: 'directLinkedIn.dailyLimitReached', reference: 'linkedin-1042'}, 429, {'Retry-After': '3600'})); + expect(details_of(await failure('linkedin-message', {body: TEXT}, LINKEDIN_OPTS))).toStrictEqual({limit: 'daily', + reference: 'linkedin-1042'}); + }); + + it('a refusal without them carries no details, and the output is what it was', async()=>{ + for (const res of [json({code: 'contact.renderingFailed', detail: 'Unclosed block at line 2.'}, 400), + json({code: 'contact.somethingNew'}, 400), json('Bad Request', 400)]) + { + mock_fetch.mockReset(); + answer(res); + const e = await failure('send-email', EMAIL, EMAIL_OPTS); + expect(details_of(e)).toBeUndefined(); + expect(JSON.stringify((e as {to_json: () => unknown}).to_json())).not.toContain('details'); + } + }); +}); diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 1279933..b306a27 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -308,7 +308,8 @@ const LATER = 'With --send-after Reply holds the send until that moment, given w + 'is idempotency_key.in_use, and the same key on a different send is idempotency_key.reused. Neither sends anything.\n' + 'A repeat of a send given a person\'s fields answers contact.already_held first, since the first one created the\n' + 'contact: that is safe too, as nothing is sent twice. idempotency_key.reused names the send the key was first taken\n' - + 'for in details: reference, state and send_after, each only when Reply gives it.\n'; + + 'for in details: reference, state and send_after, each only when Reply gives it. Any other refusal of a send Reply\n' + + 'already holds names that send the same way, beside the refusal\'s own details; its code is the refusal\'s own.\n'; // The refusals of a send's key, the same on every direct send, after each send's own. const KEY_CODES = ['idempotency_key.in_use', 'idempotency_key.reused']; diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index d3e69bc..bb1b974 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -1,7 +1,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, reply_code_of, detail_of, open_session, type Answer} from './call'; +import {call_reply, expect_object, refusal, is_object, reply_code_of, detail_of, open_session, type Answer} from './call'; import {parse_id, 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'; @@ -186,14 +186,10 @@ const KEY_IN_USE: Refusal = { hint: 'Run it again with the same key once that send is made: Reply answers a repeat with the send the key first made.', }; // Reply holds the send the key was first taken for, and may name it: a repeat built differently from -// the first attempt answers reused, so the caller still learns which send that was. +// the first attempt answers reused, so the caller still learns which send that was (send_refusal). const KEY_REUSED: Refusal = { status: 409, code: 'idempotency_key.reused', title: 'Reply already took this idempotency key for a different send, so nothing was sent.', hint: 'Give each new send a key of its own.', - details: body=>{ - const held = picked(HELD_KEYS, body); - return Object.keys(held).length === 0 ? undefined : held; - }, }; const KEY_REFUSALS: Record> = { email: {'contact.idempotencyKeyInUse': KEY_IN_USE, 'contact.idempotencyKeyReused': KEY_REUSED}, @@ -227,7 +223,7 @@ const known_refusal = (a: Answer, table: Record): Operation_err : undefined; }; -const send_refusal = (a: Answer, contact_id: number, by: Channel): Operation_error=>{ +const refusal_of_send = (a: Answer, contact_id: number, by: Channel): Operation_error=>{ const reply_code = reply_code_of(a); if (a.status === 404 && (reply_code === 'contact.notFound' || reply_code === 'directLinkedIn.contactNotFound')) { @@ -244,6 +240,19 @@ const send_refusal = (a: Answer, contact_id: number, by: Channel): Operation_err ?? 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 held = is_object(a.data) ? picked(HELD_KEYS, a.data) : {}; + if (Object.keys(held).length > 0) + { + e.details = {...e.details, ...held}; + } + return e; +}; + const positive_integer = (v: unknown): number | null=> typeof v === 'number' && Number.isSafeInteger(v) && v > 0 ? v : null; From 3eb394477250d38935b38559967d7e467a6a97e2 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 17:56:47 -0700 Subject: [PATCH 22/24] test: a 500 on any of the five direct sends is outcome.unknown, sent once Reply answers 500 for an exception escaping a send, on the LinkedIn routes as on the email one. No row held that for a 500 itself, so the answers that may hide a send now include it, on every send: exit 3, one call, and the hint that a repeat may send it twice. --- src/__tests__/operations/direct-send.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index d889974..eac8770 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -275,6 +275,8 @@ describe('every direct send', ()=>{ const answers: [string, ()=>void][] = [ ['lost answer', ()=>{ mock_fetch.mockRejectedValueOnce(lost_connection()); }], ['503', ()=>answer(json({title: 'Service Unavailable'}, 503))], + // An exception escaping a send, on the email route and the LinkedIn ones alike. + ['500', ()=>answer(json({title: 'Internal Server Error', status: 500}, 500, {'Content-Type': 'application/problem+json'}))], ['uncoded 502', ()=>answer(json('bad gateway', 502))], ['201', ()=>answer(json({}, 201))], ['unreadable 200', ()=>answer(json('ok', 200))], From 947afab4ed78f17e3c9982b28cdacfc05cbd1eef Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 18:02:52 -0700 Subject: [PATCH 23/24] feat: a 400 to a direct send with neither a code nor errors[] is outcome.unknown Reply answers an exception escaping a send, on the LinkedIn routes as well, with a 400 whose body carries no code and no errors[], and the send may already be made. It is now outcome.unknown (exit 3) with the hint that a repeat may send twice, on the send call only. A 400 with errors[], a page that is not JSON, and the import call of a send given a person's fields map as before. --- README.md | 8 +-- src/__tests__/operations/commands.test.ts | 2 + src/__tests__/operations/direct-send.test.ts | 57 ++++++++++++++++++++ src/operations/commands.ts | 4 +- src/operations/direct-send.ts | 12 +++++ 5 files changed, 79 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 6295391..9de4faa 100644 --- a/README.md +++ b/README.md @@ -399,9 +399,11 @@ reply schedule list --json `inbox reply`, `sequence create` and the five direct sends are the work commands that are not safe to re-run. On exit 3 (outcome unknown) a reply or a send may already have gone, and running it again may -send it twice, unless the hint says nothing was sent: a send whose contact's import lost its answer -was never made, and its hint says so; run again, it answers `contact.already_held` if that import did -create the contact. An `--idempotency-key` does not change this: a Reply that does not know the +send it twice, unless the hint says nothing was sent. A direct send's exit 3 comes from a lost +answer, a 5xx, or a 400 to the send whose JSON carries neither a `code` nor `errors[]`, which is +Reply failing while it made the send; a 400 with `errors[]` is `reply.invalid_request` and sent +nothing. A send whose contact's import lost its answer was never made, and its hint says so; run +again, it answers `contact.already_held` if that import did create the contact. An `--idempotency-key` does not change this: a Reply that does not know the header yet would make the send again. For `inbox reply`, read the thread with `reply inbox get` before trying again. For `sequence create`, Reply allows two sequences of one name, so after exit 3 look the name up with diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index 3155318..9f31b47 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -300,6 +300,8 @@ describe('operations/commands', ()=>{ + 'state and send_after, each only when Reply gives it'); expect(flat, text).toContain('Any other refusal of a send Reply already holds names that send the same way, beside the ' + 'refusal\'s own details; its code is the refusal\'s own'); + expect(flat, text).toContain('A 400 to the send with neither a code nor errors[] is Reply failing while it made the send: ' + + 'like a 5xx or a lost answer, it is outcome.unknown (exit 3)'); // Exactly the codes its endpoint publishes, then the shared ones, as the help lists them. const listed = text.split('\nErrors')[1].split('\nExit codes')[0].split('\n').slice(1).map(l=>l.trim()); expect(listed, name).toEqual([...codes, 'idempotency_key.in_use', 'idempotency_key.reused', 'access.denied', 'access.feature_unavailable', 'rate_limited', 'reply.unavailable', diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index eac8770..5f7bf35 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -528,6 +528,8 @@ describe('a direct send to a person given by their fields', ()=>{ 'contact.invalid_linkedin_url', 1], [[nobody(), nobody(), json({code: 'contact.limitExceeded', detail: 'Contact limit reached.'}, 400)], 'account.contact_limit_reached', 1], [[nobody(), nobody(), json({items: [{id: null, status: 'failed', error: 'Invalid data'}]})], 'reply.refused', 1], + // A 400 with neither a code nor errors[] is read as Reply's exception only on the send call, never on the import. + [[nobody(), nobody(), json({title: 'Bad Request', status: 400}, 400, {'Content-Type': 'application/problem+json'})], 'reply.refused', 1], ]; for (const [answers, code, exit_code] of cases) { @@ -959,3 +961,58 @@ describe('a refused send that Reply holds a row for', ()=>{ } }); }); + +describe('a 400 on the send call with neither a code nor errors[]', ()=>{ + const SENDS: [Direct_send_name, unknown, Direct_send_opts][] = [ + ['send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS], + ['linkedin-connect', {note: NOTE}, LINKEDIN_OPTS], + ['linkedin-message', {body: TEXT}, LINKEDIN_OPTS], + ['linkedin-inmail', {subject: SUBJECT, body: TEXT}, LINKEDIN_OPTS], + ['linkedin-voice', {script: SCRIPT}, LINKEDIN_OPTS], + ]; + const problem = (body: unknown)=>json(body, 400, {'Content-Type': 'application/problem+json'}); + + it('is Reply\'s exception path: outcome.unknown (exit 3), made once, and a repeat may send it twice', async()=>{ + for (const [name, message, opts] of SENDS) + { + for (const [label, res] of [['problem', ()=>problem({title: 'Internal error', status: 400})], ['json', ()=>json({title: 'Internal error'}, 400)]] as const) + { + mock_fetch.mockReset(); + answer(res()); + const e = await failure(name, message, opts); + expect(e, `${name} ${label}`).toMatchObject({code: 'outcome.unknown', exit_code: 3, status: 400, ids: {contact_id: 456}}); + expect((e as {reply_code?: string}).reply_code, `${name} ${label}`).toBeUndefined(); + expect((e as {hint?: string}).hint ?? '', `${name} ${label}`).toContain('may send it twice'); + expect(mock_fetch, `${name} ${label}`).toHaveBeenCalledTimes(1); + } + } + }); + + it('keeps the send it names under details, should Reply give one', async()=>{ + answer(problem({title: 'Internal error', status: 400, reference: 'email-1001', state: 'failed'})); + const e = await failure('send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS); + expect(e).toMatchObject({code: 'outcome.unknown', exit_code: 3, details: {reference: 'email-1001', state: 'failed'}}); + }); + + it('with errors[] it is a request Reply refused as given, and a page that is not JSON maps as before', async()=>{ + for (const [name, message, opts] of SENDS) + { + const cases: [string, ()=>Response, string][] = [ + ['errors', ()=>problem({title: 'Validation failed', status: 400, errors: [{pointer: '/body', detail: 'must not be empty'}]}), + 'reply.invalid_request'], + ['empty errors', ()=>problem({title: 'Validation failed', status: 400, errors: []}), 'reply.invalid_request'], + ['html', ()=>new Response('Bad Request', {status: 400, headers: {'Content-Type': 'text/html'}}), 'reply.refused'], + ['text', ()=>new Response('Bad Request', {status: 400, headers: {'Content-Type': 'text/plain'}}), 'reply.refused'], + ['empty', ()=>new Response(null, {status: 400}), 'reply.refused'], + ]; + for (const [label, res, code] of cases) + { + mock_fetch.mockReset(); + answer(res()); + const e = await failure(name, message, opts); + expect(e, `${name} ${label}`).toMatchObject({code, exit_code: 1, status: 400}); + expect(mock_fetch, `${name} ${label}`).toHaveBeenCalledTimes(1); + } + } + }); +}); diff --git a/src/operations/commands.ts b/src/operations/commands.ts index b306a27..674bdff 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -309,7 +309,9 @@ const LATER = 'With --send-after Reply holds the send until that moment, given w + 'A repeat of a send given a person\'s fields answers contact.already_held first, since the first one created the\n' + 'contact: that is safe too, as nothing is sent twice. idempotency_key.reused names the send the key was first taken\n' + 'for in details: reference, state and send_after, each only when Reply gives it. Any other refusal of a send Reply\n' - + 'already holds names that send the same way, beside the refusal\'s own details; its code is the refusal\'s own.\n'; + + 'already holds names that send the same way, beside the refusal\'s own details; its code is the refusal\'s own.\n' + + 'A 400 to the send with neither a code nor errors[] is Reply failing while it made the send: like a 5xx or a lost\n' + + 'answer, it is outcome.unknown (exit 3). A 400 with errors[] is reply.invalid_request, and nothing was sent.\n'; // The refusals of a send's key, the same on every direct send, after each send's own. const KEY_CODES = ['idempotency_key.in_use', 'idempotency_key.reused']; diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index bb1b974..f88a7bb 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -223,7 +223,19 @@ const known_refusal = (a: Answer, table: Record): Operation_err : undefined; }; +// An exception escaping a send reaches the caller as a 400 whose JSON carries neither a code nor +// errors[]: the send may already be made, as on a 5xx. A model validation names its fields in +// errors[], and a page that is not JSON is no exception of Reply's; both stay refusals. +const exception_of_send = (a: Answer): boolean=> + a.status === 400 && is_object(a.data) && a.data.code === undefined && a.data.errors === undefined; + const refusal_of_send = (a: Answer, contact_id: number, by: Channel): Operation_error=>{ + if (exception_of_send(a)) + { + return new Unknown_outcome_error('Reply failed while handling the send; it may or may not have been made.', { + status: a.status, detail: detail_of(a), + }); + } const reply_code = reply_code_of(a); if (a.status === 404 && (reply_code === 'contact.notFound' || reply_code === 'directLinkedIn.contactNotFound')) { From 2eb5d63c58d94f91b5719181c7e68f2d3a10e7d3 Mon Sep 17 00:00:00 2001 From: Artem Kosolap Date: Wed, 28 Oct 2026 18:19:21 -0700 Subject: [PATCH 24/24] feat: direct-send get and cancel check the reference against the form of Reply's route Reply's route takes a reference only as email- or linkedin-, n from 1 and at most ten digits, and answers any other with a bare 404, the answer of a Reply without the route at all. Both commands now check that form before any call and refuse anything else as usage.reference (exit 2), with a message that names the form and does not repeat the input. A bare 404 on these commands therefore always means the route is absent. The rule refusing . and .. is gone, since neither has the form; nothing else is read from the reference, and the form leaves nothing to encode. The help and the README state the form and what the bare 404 then means. --- README.md | 10 ++++--- src/__tests__/operations/commands.test.ts | 5 ++++ src/__tests__/operations/direct-sends.test.ts | 26 ++++++++++++------- src/operations/commands.ts | 21 ++++++++------- src/operations/direct-sends.ts | 16 +++++++----- 5 files changed, 47 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 9de4faa..ab3cee6 100644 --- a/README.md +++ b/README.md @@ -327,9 +327,10 @@ schedule list`). The answer then adds Reply's `reference`, `send_after` and `sta Reply gives it. `status: "sent"` means Reply took the send, and `state`, when present, says whether it has gone out: `queued` or `sending` is not yet, then `sent`, `failed` or `cancelled`. `reply direct-send get ` reads the send later, and `reply direct-send cancel ` stops -one that has not gone out; the reference is Reply's, passed on as given, except that `.` and `..` -are refused (exit 2), since a path reads either as a step up. An answer without `state` -comes from a Reply that does not know these flags yet: it sent at once, as without them. +one that has not gone out. The reference is Reply's, `email-` or `linkedin-`, the form +Reply's route takes: a reference of any other form is refused before any call (`usage.reference`, +exit 2), and nothing else is read from it. An answer without `state` comes from a Reply that does +not know these flags yet: it sent at once, as without them. `--idempotency-key` goes to Reply as the `Idempotency-Key` header, never in the body. A Reply that knows the header answers a repeat with the same key with the send the key first made; while that @@ -377,7 +378,8 @@ reply inbox changes --cursor AQjfObhYHZgAAADjVg --json ``` A Reply that does not have `direct-send get`, `direct-send cancel` or the feed yet answers -`reply.refused` with status 404 and no `reply_code`. +`reply.refused` with status 404 and no `reply_code`. A reference of any other form never leaves the +CLI, so on the two `direct-send` commands that 404 means this Reply has no such route. `reply schedule list` gives every sending schedule the account can use, in one answer and in the order Reply gives them: its `time_zone_id` as Reply holds it, a Windows time zone identifier such as diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index 9f31b47..5da9511 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -47,6 +47,11 @@ describe('operations/commands', ()=>{ expect(flat, name).toContain('The reference is Reply\'s, from the answer of a send made with --send-after'); expect(flat, name).toContain('state is Reply\'s own word: queued or sending is not yet sent, then sent, failed or cancelled'); expect(flat, name).toContain('A Reply without this route answers reply.refused with status 404 and no reply_code'); + expect(flat, name).toContain('email- or linkedin-, the form Reply\'s route takes'); + expect(flat, name).toContain('any other form is refused before any call (usage.reference, exit 2), and nothing else is read from it'); + expect(flat, name).toContain('a reference of any other form never leaves the CLI, so that 404 means this Reply has no such route'); + expect(flat, name).not.toContain('step up'); + expect(c.registeredArguments[0].description, name).toContain('email- or linkedin-'); expect(flat, name).toContain('failure_code, missing_variables, rendered_subject and rendered_body are added only when Reply gives them'); expect(flat, name).toContain('failure_reason is a sentence for a person, never parsed; failure_code is Reply\'s code for the failure'); } diff --git a/src/__tests__/operations/direct-sends.test.ts b/src/__tests__/operations/direct-sends.test.ts index 1eaa0b6..0abbd10 100644 --- a/src/__tests__/operations/direct-sends.test.ts +++ b/src/__tests__/operations/direct-sends.test.ts @@ -84,23 +84,29 @@ describe('direct-send get', ()=>{ } }); - it('sends the reference as given, encoded into the path and never checked or parsed', async()=>{ - for (const [reference, path] of [['ds_8F2k', 'ds_8F2k'], ['a/b c?d', 'a%2Fb%20c%3Fd'], ['email-0', 'email-0'], - ['a.b', 'a.b'], ['...', '...'], ['.a', '.a'], [' ..', '%20..']]) + it('sends a reference of the form Reply\'s route takes as given: email- or linkedin-, n from 1 and at most ten digits', async()=>{ + for (const reference of ['email-1', 'linkedin-42', 'email-9999999999', 'email-1001']) { - mock_fetch.mockReset(); - answer(json({...QUEUED, reference})); - await get(reference); - expect(sent()[0].url, reference).toBe(`https://api/v3/direct-sends/${path}`); + for (const [fn, suffix] of [[get, ''], [cancel, '/cancel']] as const) + { + mock_fetch.mockReset(); + answer(json({...QUEUED, reference})); + await fn(reference); + expect(sent()[0].url, reference).toBe(`https://api/v3/direct-sends/${reference}${suffix}`); + } } }); - it('refuses . and .. before any call: a path segment of either would be read as a step up the path, not as a reference', async()=>{ - for (const dots of ['.', '..']) + it('refuses any other reference before any call, so a bare 404 always means the route is absent', async()=>{ + const malformed = ['email-0', 'email-01', 'email-12345678901', 'sms-1', 'email-', 'email-1a', ' email-1', 'email-1 ', 'EMAIL-1', + 'email--1', 'linkedin', '.', '..', 'a.b', '...', '.a', ' ..', 'a/b c?d', 'ds_8F2k', 'email-1/cancel', 'email-1\n']; + for (const reference of malformed) { for (const fn of [handle_direct_send_get, handle_direct_send_cancel]) { - expect(await failure(()=>fn(dots, ctx(), {})), `${fn.name} ${dots}`).toMatchObject({code: 'usage.reference', exit_code: 2}); + const e = await failure(()=>fn(reference, ctx(), {})); + expect(e, `${fn.name} ${JSON.stringify(reference)}`).toMatchObject({code: 'usage.reference', exit_code: 2}); + expect((e as Error).message, JSON.stringify(reference)).toContain('email- or linkedin-'); } } expect(mock_fetch).not.toHaveBeenCalled(); diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 674bdff..c96e5e7 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -579,17 +579,18 @@ const direct_send_command = new Command('direct-send').description('Read or canc const DIRECT_SEND = 'Result: {"reference","channel","contact_id","state","send_after","sent_at","message_id","failure_reason",\n' + '"cancelled_at"}, Reply\'s fields under these names, each null when Reply gives none. The reference is Reply\'s, from the\n' - + 'answer of a send made with --send-after; it is passed on as given and never read, except that . and .. are refused\n' - + '(usage.reference, exit 2), since a path reads either as a step up. state is Reply\'s own word: queued\n' - + 'or sending is not yet sent, then sent, failed or cancelled. failure_code, missing_variables, rendered_subject and\n' - + 'rendered_body are added only when Reply gives them: failure_reason is a sentence for a person, never parsed;\n' - + 'failure_code is Reply\'s code for the failure, the one to branch on. missing_variables lists the template variables\n' - + 'Reply could not fill, and rendered_subject and rendered_body are the text as Reply filled it in. A Reply without this\n' - + 'route answers reply.refused with status 404 and no reply_code; direct_send.not_found is a reference that Reply has no\n' - + 'send for.\n'; + + 'answer of a send made with --send-after: email- or linkedin-, the form Reply\'s route takes. A reference of\n' + + 'any other form is refused before any call (usage.reference, exit 2), and nothing else is read from it. state is\n' + + 'Reply\'s own word: queued or sending is not yet sent, then sent, failed or cancelled. failure_code,\n' + + 'missing_variables, rendered_subject and rendered_body are added only when Reply gives them: failure_reason is a\n' + + 'sentence for a person, never parsed; failure_code is Reply\'s code for the failure, the one to branch on.\n' + + 'missing_variables lists the template variables Reply could not fill, and rendered_subject and rendered_body are the\n' + + 'text as Reply filled it in. A Reply without this route answers reply.refused with status 404 and no reply_code; a\n' + + 'reference of any other form never leaves the CLI, so that 404 means this Reply has no such route.\n' + + 'direct_send.not_found is a reference that Reply has no send for.\n'; direct_send_command.command('get') - .argument('', 'The send\'s reference, as a send made with --send-after answered it') + .argument('', 'The send\'s reference, email- or linkedin-, as a send made with --send-after answered it') .description('One direct send as Reply holds it: whether it has gone out, when, and why it failed') .addHelpText('after', help([ex('direct-send get email-1001')], ['direct_send.not_found', 'direct_send.not_owned'], false, DIRECT_SEND)) .action(run(async(cmd)=>{ @@ -598,7 +599,7 @@ direct_send_command.command('get') })); direct_send_command.command('cancel') - .argument('', 'The send\'s reference, as a send made with --send-after answered it') + .argument('', 'The send\'s reference, email- or linkedin-, as a send made with --send-after answered it') .description('Stop a direct send that has not gone out yet') .addHelpText('after', help([ex('direct-send cancel email-1001')], ['direct_send.not_found', 'direct_send.not_owned', 'direct_send.already_sent', 'direct_send.already_failed'], true, diff --git a/src/operations/direct-sends.ts b/src/operations/direct-sends.ts index 336d7d8..188b0cd 100644 --- a/src/operations/direct-sends.ts +++ b/src/operations/direct-sends.ts @@ -5,20 +5,22 @@ import {print_result} from './result'; import type {Op_globals} from './options'; import type {Cli_context} from '../context'; -// The reference is Reply's and opaque: it is sent as given, encoded into the path, and never read -// beyond refusing what cannot name a send. +// Reply's route takes exactly this form and answers anything else with a bare 404, as it does when it +// has no such route at all. Checking the form here keeps that 404 meaning only the latter; nothing else +// is read from the reference, and the form leaves nothing to encode. +const REFERENCE = /^(email|linkedin)-[1-9]\d{0,9}$/; + const path_of = (reference: string): string=>{ if (reference.trim() === '') { throw new UsageError('No reference was given.', {code: 'usage.reference', hint: 'A send made with --send-after answers its reference.'}); } - // Encoding leaves a dot as it is, and a path segment of . or .. is read as a step up the path: the - // call would reach another route. - if (reference === '.' || reference === '..') + if (!REFERENCE.test(reference)) { - throw new UsageError(`${reference} is not a reference.`, {code: 'usage.reference', hint: 'A send made with --send-after answers its reference.'}); + throw new UsageError('That is not a reference Reply gives: email- or linkedin-, n from 1.', + {code: 'usage.reference', hint: 'A send made with --send-after answers its reference.'}); } - return `/v3/direct-sends/${encodeURIComponent(reference)}`; + return `/v3/direct-sends/${reference}`; }; // What Reply says of the text it rendered and of a failure's code, each only when it gives it, as text