@mccaskie-labs/workbench-nudges 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/nudges.js ADDED
@@ -0,0 +1,381 @@
1
+ // createNudges: follow-up nudges (docs/capabilities/09-follow-up-nudges.md).
2
+ // The app starts a rule when something goes out (a quote sent), touches the
3
+ // subject when something happens (they replied, it was booked), and calls
4
+ // tick() from its own cron every 15 minutes. When a step comes due, tick()
5
+ // drafts the follow-up with the reply drafter (capability 4) from the latest
6
+ // facts, so the draft knows the date was booked meanwhile, and the owner sees
7
+ // it in the app's Waiting for you list and the daily email digest.
8
+ //
9
+ // Nudges remind the business. They never message the business's customer:
10
+ // the owner copies the draft and sends it.
11
+ //
12
+ // Use it with the service client, server side: the functions are the service
13
+ // role's only (see migration.ts).
14
+ import { checkNudgeConfig } from "./config.js";
15
+ import { NudgesError } from "./errors.js";
16
+ import { addDuration, clockMinutes, durationWords, minutesIn, outOfQuiet, todayIn } from "./time.js";
17
+ import { NUDGE_WORDS } from "./words.js";
18
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
19
+ const EVENT = /^[a-z][a-z0-9_]{0,39}$/;
20
+ const LEASE_MS = 10 * 60_000;
21
+ const NINETY_DAYS_MS = 90 * 86_400_000;
22
+ async function call(db, what, fn, args) {
23
+ const { data, error } = await db.rpc(fn, args);
24
+ if (error)
25
+ throw new NudgesError("store_failed", `${what}: ${error.message || "no answer"}${error.code ? ` (${error.code})` : ""}`);
26
+ return data;
27
+ }
28
+ function text(v, what, max) {
29
+ if (typeof v !== "string" || !v.trim() || v.trim().length > max)
30
+ throw new NudgesError("bad_input", `${what} must be text, 1 to ${max} characters`);
31
+ return v.trim();
32
+ }
33
+ function subjectOf(v) {
34
+ const s = v;
35
+ if (!s || typeof s !== "object")
36
+ throw new NudgesError("bad_input", "subject must be { type, id }, such as { type: 'enquiry', id }");
37
+ return { type: text(s.type, "subject.type", 60), id: text(s.id, "subject.id", 200) };
38
+ }
39
+ function nudgeId(v) {
40
+ if (typeof v !== "string" || !UUID.test(v))
41
+ throw new NudgesError("bad_input", "nudgeId must be a nudge's id");
42
+ return v;
43
+ }
44
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
45
+ const iso = (v) => (typeof v === "string" && v ? new Date(v).toISOString() : null);
46
+ /** A row with its times as ISO 8601 in UTC (Postgres writes +00:00). */
47
+ function norm(n) {
48
+ return { ...n, due_at: iso(n.due_at), made_due_at: iso(n.made_due_at), started_at: iso(n.started_at), ended_at: iso(n.ended_at) };
49
+ }
50
+ /**
51
+ * The Gateway's Idempotency-Key for one email to one owner: the same for a
52
+ * retry of the same digest or due note, and inside workbench-email's
53
+ * [A-Za-z0-9._:-]{1,255}. An email address (its @ and +) or an app's own
54
+ * account id can't go in as written, so they go in as a hash.
55
+ */
56
+ export async function mailKey(key, email) {
57
+ const d = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${key}\n${email.trim().toLowerCase()}`));
58
+ return `nudges:${[...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
59
+ }
60
+ /** The one line a due nudge shows with, in English. */
61
+ function reasonText(rule, step, code) {
62
+ const w = NUDGE_WORDS.en;
63
+ const base = w["reason.no_reply"].replace("{after}", durationWords(rule.steps[step - 1]?.after ?? rule.steps[0].after));
64
+ return code === "no_reply" ? base : `${base}. ${w[`reason.${code}`]}`;
65
+ }
66
+ export function createNudges(opts) {
67
+ const config = checkNudgeConfig(opts.rules);
68
+ const { db } = opts;
69
+ const now = opts.now ?? (() => new Date());
70
+ const tz = config.time_zone;
71
+ const quiet = config.quiet_hours;
72
+ const feature = config.plans?.feature ?? "nudges";
73
+ const meter = config.plans?.meter;
74
+ const batch = opts.batch ?? 200;
75
+ const digestAt = clockMinutes(config.digest_at ?? quiet?.to ?? "08:00");
76
+ function ruleOf(name) {
77
+ if (typeof name !== "string" || !Object.hasOwn(config.rules, name))
78
+ throw new NudgesError("unknown_rule", `${String(name)} isn't a rule in workbench/nudges.json`);
79
+ return config.rules[name];
80
+ }
81
+ /** When step `step` (from 1) comes due, counted from `from`, moved out of the quiet hours. */
82
+ const stepAt = (rule, step, from) => outOfQuiet(addDuration(from, rule.steps[step - 1].after, tz), quiet, tz);
83
+ async function get(id) {
84
+ const n = await call(db, "get", "nudges_get", { p_nudge: nudgeId(id) });
85
+ return n ? norm(n) : null;
86
+ }
87
+ async function end(id, status, reason, claim, at) {
88
+ return await call(db, "end", "nudges_end", { p_nudge: id, p_status: status, p_reason: reason, p_claim: claim, p_now: at.toISOString() });
89
+ }
90
+ async function schedule(id, step, due, status, from, at) {
91
+ return await call(db, "schedule", "nudges_schedule", { p_nudge: id, p_step: step, p_due: due.toISOString(), p_status: status, p_from: [...from], p_now: at.toISOString() });
92
+ }
93
+ async function mail(account, kind, count, key) {
94
+ if (!opts.mailer || !opts.owners)
95
+ return 0;
96
+ const owners = await opts.owners(account);
97
+ let sent = 0;
98
+ for (const o of owners) {
99
+ if (!o || typeof o.email !== "string" || !o.email.includes("@"))
100
+ continue;
101
+ const w = NUDGE_WORDS[o.language ?? config.language ?? "en"] ?? NUDGE_WORDS.en;
102
+ const fill = (s) => s.replace("{count}", String(count));
103
+ const subject = fill(count === 1 ? w[`email.${kind}.subject_one`] : w[`email.${kind}.subject`]);
104
+ const url = opts.listUrl?.(account);
105
+ const body = [fill(count === 1 ? w["email.body_one"] : w["email.body"]), ...(url ? ["", `${w["email.open"]}: ${url}`] : []), "", w["email.footer"]].join("\n");
106
+ await opts.mailer.send({ to: o.email, subject, text: body, template: `nudges.${kind}`, idempotencyKey: await mailKey(key, o.email) });
107
+ sent++;
108
+ }
109
+ return sent;
110
+ }
111
+ return {
112
+ rules: config,
113
+ async start(req) {
114
+ if (!isObj(req))
115
+ throw new NudgesError("bad_input", "start takes { rule, account, subject }");
116
+ const rule = ruleOf(req.rule);
117
+ const account = text(req.account, "account", 200);
118
+ const subject = subjectOf(req.subject);
119
+ let facts = null;
120
+ if (req.facts !== undefined && req.facts !== null) {
121
+ if (!isObj(req.facts))
122
+ throw new NudgesError("bad_input", "facts must be an object");
123
+ if (new TextEncoder().encode(JSON.stringify(req.facts)).byteLength > 4000)
124
+ throw new NudgesError("bad_input", "facts must be up to 4 KB: pass ids and dates, and let refresh load the rest");
125
+ facts = req.facts;
126
+ }
127
+ const startedAt = req.startedAt ?? now();
128
+ if (!(startedAt instanceof Date) || Number.isNaN(startedAt.getTime()))
129
+ throw new NudgesError("bad_input", "startedAt must be a date");
130
+ if (opts.plans) {
131
+ const can = await opts.plans.can(account, feature);
132
+ if (!can.ok)
133
+ throw new NudgesError("not_allowed", `the account's plan doesn't include ${feature} (${can.reason ?? "not_on_plan"})`);
134
+ }
135
+ const n = await call(db, "start", "nudges_start", {
136
+ p_rule: req.rule,
137
+ p_account: account,
138
+ p_type: subject.type,
139
+ p_id: subject.id,
140
+ p_due: stepAt(rule, 1, startedAt).toISOString(),
141
+ p_email: rule.email_owner ?? "daily_digest",
142
+ p_facts: facts,
143
+ p_now: startedAt.toISOString(),
144
+ });
145
+ return norm(n);
146
+ },
147
+ async touch(subj, kind) {
148
+ const subject = subjectOf(subj);
149
+ if (typeof kind !== "string" || !EVENT.test(kind))
150
+ throw new NudgesError("bad_input", "kind must be an event name such as they_replied");
151
+ const at = now();
152
+ const active = (await call(db, "touch", "nudges_active_for", { p_type: subject.type, p_id: subject.id })) ?? [];
153
+ for (const n of active) {
154
+ const rule = config.rules[n.rule];
155
+ if (!rule)
156
+ continue;
157
+ if (rule.stops_on.includes(kind)) {
158
+ await end(n.id, "stopped", kind, null, at);
159
+ }
160
+ else if (rule.restarts_on?.includes(kind)) {
161
+ await schedule(n.id, 1, stepAt(rule, 1, at), "waiting", [n.status], at);
162
+ }
163
+ else if (kind === "we_replied") {
164
+ // The owner sent something: a due step is done and the next counts from now; a waiting one starts its count again.
165
+ const next = n.status === "due" ? n.step + 1 : n.step;
166
+ if (next > rule.steps.length)
167
+ await end(n.id, "done", "steps_done", null, at);
168
+ else
169
+ await schedule(n.id, next, stepAt(rule, next, at), "waiting", [n.status], at);
170
+ }
171
+ }
172
+ },
173
+ async snooze(id, until) {
174
+ const nid = nudgeId(id);
175
+ const at = now();
176
+ if (!(until instanceof Date) || Number.isNaN(until.getTime()) || until.getTime() <= at.getTime() || until.getTime() - at.getTime() > NINETY_DAYS_MS) {
177
+ throw new NudgesError("bad_input", "until must be a time in the next 90 days");
178
+ }
179
+ const n = await get(nid);
180
+ if (!n || !["waiting", "due", "snoozed"].includes(n.status))
181
+ throw new NudgesError("unknown_nudge", "snooze: no such nudge, or it has ended");
182
+ if (!(await schedule(nid, n.step, until, "snoozed", ["waiting", "due", "snoozed"], at)))
183
+ throw new NudgesError("unknown_nudge", "snooze: the nudge has ended");
184
+ },
185
+ async dismiss(id, reason) {
186
+ const nid = nudgeId(id);
187
+ const why = reason === undefined || reason === "" ? "dismissed" : text(reason, "reason", 200);
188
+ if (!(await end(nid, "dismissed", why, null, now())))
189
+ throw new NudgesError("unknown_nudge", "dismiss: no such nudge, or it has ended");
190
+ },
191
+ async due(account) {
192
+ const rows = (await call(db, "due", "nudges_due", { p_account: text(account, "account", 200) })) ?? [];
193
+ return rows.map((row) => {
194
+ const r = norm(row);
195
+ const rule = config.rules[r.rule];
196
+ const code = (r.reason ?? "no_reply");
197
+ return {
198
+ id: r.id,
199
+ rule: r.rule,
200
+ subject: r.subject,
201
+ step: r.step,
202
+ due_at: r.due_at,
203
+ ...(r.draft ? { draft: r.draft } : {}),
204
+ reason: rule ? reasonText(rule, r.step, code) : NUDGE_WORDS.en["reason.no_reply"].replace("{after}", "a while"),
205
+ reason_code: code,
206
+ made_due_at: r.made_due_at ?? r.due_at,
207
+ steps: rule?.steps.length ?? r.step,
208
+ after: rule?.steps[r.step - 1]?.after ?? "",
209
+ };
210
+ });
211
+ },
212
+ get,
213
+ async tick() {
214
+ const at = now();
215
+ const claim = crypto.randomUUID();
216
+ const out = { made_due: 0, drafted: 0, emailed: 0, ended: 0 };
217
+ const rows = (await call(db, "tick", "nudges_claim", {
218
+ p_claim: claim,
219
+ p_now: at.toISOString(),
220
+ p_until: new Date(at.getTime() + LEASE_MS).toISOString(),
221
+ p_limit: batch,
222
+ })) ?? [];
223
+ for (const n of rows) {
224
+ const rule = config.rules[n.rule];
225
+ if (!rule) {
226
+ if (await end(n.id, "stopped", "unknown_rule", claim, at))
227
+ out.ended++;
228
+ continue;
229
+ }
230
+ // A due step whose time has passed moves on; after the last, the nudge ends.
231
+ const step = n.status === "due" ? n.step + 1 : Math.min(n.step, rule.steps.length);
232
+ if (step > rule.steps.length) {
233
+ if (await end(n.id, "done", "steps_done", claim, at))
234
+ out.ended++;
235
+ continue;
236
+ }
237
+ const base = n.facts ?? {};
238
+ let fresh = {};
239
+ if (opts.refresh) {
240
+ try {
241
+ fresh = await opts.refresh({ id: n.id, rule: n.rule, account: n.account, subject: n.subject, step, facts: base });
242
+ }
243
+ catch {
244
+ // The app couldn't load the facts: try again next tick.
245
+ await call(db, "tick", "nudges_release", { p_nudge: n.id, p_claim: claim });
246
+ continue;
247
+ }
248
+ }
249
+ if (fresh === null || fresh.stop) {
250
+ if (await end(n.id, "stopped", fresh === null ? "subject_gone" : String(fresh.stop).slice(0, 200), claim, at))
251
+ out.ended++;
252
+ continue;
253
+ }
254
+ const facts = { ...base, ...(fresh.facts ?? {}) };
255
+ if (rule.skip_if?.date_passed && typeof facts.date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(facts.date) && facts.date < todayIn(tz, at)) {
256
+ if (await end(n.id, "stopped", "date_passed", claim, at))
257
+ out.ended++;
258
+ continue;
259
+ }
260
+ const taken = facts.available === "no";
261
+ if (taken && rule.skip_if?.date_unavailable === "stop") {
262
+ if (await end(n.id, "stopped", "date_unavailable", claim, at))
263
+ out.ended++;
264
+ continue;
265
+ }
266
+ let reason = taken ? "date_unavailable" : "no_reply";
267
+ let draft = null;
268
+ if (!opts.ai)
269
+ reason = "no_ai";
270
+ else {
271
+ let allowed = true;
272
+ let useId;
273
+ if (opts.plans) {
274
+ const can = await opts.plans.can(n.account, feature);
275
+ allowed = can.ok;
276
+ if (allowed && meter) {
277
+ const use = await opts.plans.use(n.account, meter, { subject: `nudge:${n.id}`, idempotencyKey: `nudge:${n.id}:${step}:${n.due_at}` });
278
+ allowed = use.ok;
279
+ useId = use.useId;
280
+ }
281
+ }
282
+ if (!allowed)
283
+ reason = "not_on_plan";
284
+ else {
285
+ const s = rule.steps[step - 1];
286
+ const say = [s.say, taken ? "The date they asked about is now taken: offer the alternatives instead, and don't say it is free." : undefined].filter(Boolean).join(" ");
287
+ try {
288
+ draft = await opts.ai.reply({
289
+ guide: s.guide,
290
+ facts,
291
+ language: fresh.language ?? rule.language ?? config.language ?? "en",
292
+ ...(say ? { note: say } : {}),
293
+ ...(fresh.link !== undefined ? { link: fresh.link } : {}),
294
+ subject: n.subject,
295
+ account: n.account,
296
+ });
297
+ }
298
+ catch {
299
+ reason = "draft_failed";
300
+ if (useId)
301
+ await opts.plans.release(useId).catch(() => { });
302
+ }
303
+ }
304
+ }
305
+ // The next step counts from this one's due time; after the last, the nudge ends ends_after later if nobody acts.
306
+ // A tick that runs late (the cron was down) counts from now, so each step still shows before the next.
307
+ const nextFrom = (from) => (step < rule.steps.length ? stepAt(rule, step + 1, from) : addDuration(from, rule.ends_after ?? "7d", tz));
308
+ let next = nextFrom(new Date(n.due_at));
309
+ if (next.getTime() <= at.getTime())
310
+ next = nextFrom(at);
311
+ const ok = await call(db, "tick", "nudges_made_due", {
312
+ p_nudge: n.id,
313
+ p_claim: claim,
314
+ p_step: step,
315
+ p_next: next.toISOString(),
316
+ p_reason: reason,
317
+ p_draft: draft,
318
+ p_now: at.toISOString(),
319
+ });
320
+ if (!ok)
321
+ continue;
322
+ out.made_due++;
323
+ if (draft)
324
+ out.drafted++;
325
+ if (n.email === "each") {
326
+ try {
327
+ out.emailed += await mail(n.account, "due", 1, `nudge:${n.id}:${step}`);
328
+ }
329
+ catch {
330
+ // The list still shows it; an email that failed isn't sent again.
331
+ }
332
+ }
333
+ }
334
+ // The daily digest: once a day per account with something due, from digest_at.
335
+ if (opts.mailer && opts.owners && minutesIn(tz, at) >= digestAt) {
336
+ const day = todayIn(tz, at);
337
+ const counts = (await call(db, "digest", "nudges_digest_counts", {})) ?? [];
338
+ for (const c of counts) {
339
+ if (!(await call(db, "digest", "nudges_digest_claim", { p_account: c.account, p_day: day, p_due: c.due, p_now: at.toISOString() })))
340
+ continue;
341
+ try {
342
+ out.emailed += await mail(c.account, "digest", c.due, `nudges-digest:${c.account}:${day}`);
343
+ }
344
+ catch {
345
+ await call(db, "digest", "nudges_digest_release", { p_account: c.account, p_day: day });
346
+ }
347
+ }
348
+ }
349
+ return out;
350
+ },
351
+ async cleanup() {
352
+ return await call(db, "cleanup", "nudges_cleanup", {
353
+ p_now: now().toISOString(),
354
+ p_days: config.retention_days ?? 90,
355
+ p_draft_days: config.draft_days ?? 30,
356
+ });
357
+ },
358
+ };
359
+ }
360
+ /**
361
+ * The refresh for outreach contacts (subject type `outreach_contact`, rule
362
+ * supplier-no-reply with workbench-social's outreach-follow-up guide): a
363
+ * contact still waiting on a reply (contacted) gets its business and detail
364
+ * as facts; one that replied, said no or said stop ends the nudge with its
365
+ * status. Compose it with the app's own refresh for other subjects.
366
+ */
367
+ export function outreachRefresh(outreach) {
368
+ return async (n) => {
369
+ const c = await outreach.get(n.subject.id);
370
+ if (!c)
371
+ return null;
372
+ if (c.status !== "contacted")
373
+ return { stop: c.status === "do_not_contact" ? "do_not_contact" : c.status === "new" ? "subject_gone" : "they_replied" };
374
+ const facts = { business: c.business };
375
+ if (c.detail)
376
+ facts.detail = c.detail;
377
+ if (c.contact_name)
378
+ facts.contact_name = c.contact_name;
379
+ return { facts };
380
+ };
381
+ }
@@ -0,0 +1,80 @@
1
+ /** A gentle follow-up to a quote that got no reply. The facts come from the app's refresh (capability 5's latest answer). */
2
+ export declare const QUOTE_FOLLOW_UP_GUIDE: {
3
+ readonly format: 1;
4
+ readonly name: "quote-follow-up";
5
+ readonly version: 1;
6
+ readonly voice: "conversational";
7
+ readonly max_words: 50;
8
+ readonly max_questions: 1;
9
+ readonly facts: {
10
+ readonly type: "object";
11
+ readonly required: readonly ["business"];
12
+ readonly properties: {
13
+ readonly business: {
14
+ readonly type: "string";
15
+ };
16
+ readonly customer_first_name: {
17
+ readonly type: "string";
18
+ readonly "x-personal": "name";
19
+ };
20
+ readonly date: {
21
+ readonly type: "string";
22
+ readonly format: "date";
23
+ };
24
+ readonly available: {
25
+ readonly type: "string";
26
+ readonly enum: readonly ["yes", "no", "partly", "unknown"];
27
+ };
28
+ readonly alternatives: {
29
+ readonly type: "array";
30
+ readonly maxItems: 3;
31
+ readonly items: {
32
+ readonly type: "string";
33
+ readonly format: "date";
34
+ };
35
+ };
36
+ };
37
+ };
38
+ readonly guide: readonly ["Write one short, warm follow-up to the quote we sent, which the customer hasn't answered.", "Greet them by customer_first_name if we have it.", "If available is yes, say the date is still free and ask if they have any questions about the quote.", "If available is no, say sorry that the date has just been taken and offer the alternatives.", "Put the link at the end if there is one."];
39
+ readonly never: readonly ["promise a discount", "confirm a booking", "ask for payment details", "pressure them or say the offer is about to expire"];
40
+ };
41
+ /** workbench/nudges.json as the spec's example has it: quotes with no reply, and businesses that haven't answered our first message. */
42
+ export declare const STARTER_NUDGES: {
43
+ readonly format: 1;
44
+ readonly time_zone: "Asia/Manila";
45
+ readonly quiet_hours: {
46
+ readonly from: "21:00";
47
+ readonly to: "08:00";
48
+ };
49
+ readonly language: "en";
50
+ readonly max_steps: 3;
51
+ readonly rules: {
52
+ readonly "quote-no-reply": {
53
+ readonly starts_on: "quote_sent";
54
+ readonly stops_on: readonly ["they_replied", "booked", "closed"];
55
+ readonly steps: readonly [{
56
+ readonly after: "3d";
57
+ readonly guide: "quote-follow-up";
58
+ readonly say: "Gentle check-in, mention the date is still free";
59
+ }, {
60
+ readonly after: "7d";
61
+ readonly guide: "quote-follow-up";
62
+ readonly say: "Last check-in, offer an alternative date if theirs is now taken";
63
+ }];
64
+ readonly skip_if: {
65
+ readonly date_passed: true;
66
+ readonly date_unavailable: "offer_alternatives";
67
+ };
68
+ readonly email_owner: "daily_digest";
69
+ };
70
+ readonly "supplier-no-reply": {
71
+ readonly starts_on: "opener_sent";
72
+ readonly stops_on: readonly ["they_replied", "do_not_contact"];
73
+ readonly steps: readonly [{
74
+ readonly after: "4d";
75
+ readonly guide: "outreach-follow-up";
76
+ }];
77
+ readonly email_owner: "none";
78
+ };
79
+ };
80
+ };
@@ -0,0 +1,61 @@
1
+ // The starting files `npx workbench-nudges init` copies into a project:
2
+ // workbench/nudges.json with the spec's two rules, and the quote-follow-up
3
+ // reply guide (workbench/replies/) the first rule drafts with. The second
4
+ // rule drafts with workbench-social's outreach-follow-up guide (`npx
5
+ // workbench-social outreach init` writes it). The project edits them like its
6
+ // own; `npx workbench-nudges generate` and `npx workbench-ai replies
7
+ // generate` check them.
8
+ /** A gentle follow-up to a quote that got no reply. The facts come from the app's refresh (capability 5's latest answer). */
9
+ export const QUOTE_FOLLOW_UP_GUIDE = {
10
+ format: 1,
11
+ name: "quote-follow-up",
12
+ version: 1,
13
+ voice: "conversational",
14
+ max_words: 50,
15
+ max_questions: 1,
16
+ facts: {
17
+ type: "object",
18
+ required: ["business"],
19
+ properties: {
20
+ business: { type: "string" },
21
+ customer_first_name: { type: "string", "x-personal": "name" },
22
+ date: { type: "string", format: "date" },
23
+ available: { type: "string", enum: ["yes", "no", "partly", "unknown"] },
24
+ alternatives: { type: "array", maxItems: 3, items: { type: "string", format: "date" } },
25
+ },
26
+ },
27
+ guide: [
28
+ "Write one short, warm follow-up to the quote we sent, which the customer hasn't answered.",
29
+ "Greet them by customer_first_name if we have it.",
30
+ "If available is yes, say the date is still free and ask if they have any questions about the quote.",
31
+ "If available is no, say sorry that the date has just been taken and offer the alternatives.",
32
+ "Put the link at the end if there is one.",
33
+ ],
34
+ never: ["promise a discount", "confirm a booking", "ask for payment details", "pressure them or say the offer is about to expire"],
35
+ };
36
+ /** workbench/nudges.json as the spec's example has it: quotes with no reply, and businesses that haven't answered our first message. */
37
+ export const STARTER_NUDGES = {
38
+ format: 1,
39
+ time_zone: "Asia/Manila",
40
+ quiet_hours: { from: "21:00", to: "08:00" },
41
+ language: "en",
42
+ max_steps: 3,
43
+ rules: {
44
+ "quote-no-reply": {
45
+ starts_on: "quote_sent",
46
+ stops_on: ["they_replied", "booked", "closed"],
47
+ steps: [
48
+ { after: "3d", guide: "quote-follow-up", say: "Gentle check-in, mention the date is still free" },
49
+ { after: "7d", guide: "quote-follow-up", say: "Last check-in, offer an alternative date if theirs is now taken" },
50
+ ],
51
+ skip_if: { date_passed: true, date_unavailable: "offer_alternatives" },
52
+ email_owner: "daily_digest",
53
+ },
54
+ "supplier-no-reply": {
55
+ starts_on: "opener_sent",
56
+ stops_on: ["they_replied", "do_not_contact"],
57
+ steps: [{ after: "4d", guide: "outreach-follow-up" }],
58
+ email_owner: "none",
59
+ },
60
+ },
61
+ };
@@ -0,0 +1,34 @@
1
+ /** One CSS custom property the rules read, with its default. */
2
+ interface StyleVariable {
3
+ /** `--wb-<tool>-<what>`. */
4
+ name: string;
5
+ value: string;
6
+ about: string;
7
+ }
8
+ /** A rule for a class in another state, or for an element inside it. */
9
+ interface StyleState {
10
+ selector: string;
11
+ about: string;
12
+ css: string;
13
+ }
14
+ /** One class the tool puts on an element, with its default rule. */
15
+ interface StyleClass {
16
+ name: string;
17
+ element: string;
18
+ about: string;
19
+ css: string;
20
+ states?: readonly StyleState[];
21
+ }
22
+ /** Every class and variable the tool draws with. */
23
+ export interface ToolStyles {
24
+ format: 1;
25
+ tool: string;
26
+ package: string;
27
+ title: string;
28
+ prefix: string;
29
+ variables: readonly StyleVariable[];
30
+ classes: readonly StyleClass[];
31
+ }
32
+ /** The style hooks of the Waiting for you list (renderNudgeList). */
33
+ export declare const NUDGE_STYLES: ToolStyles;
34
+ export {};
package/dist/styles.js ADDED
@@ -0,0 +1,70 @@
1
+ // The look the Waiting for you list starts with (docs/capabilities-manifest.md
2
+ // §10). Every element renderNudgeList draws carries one of these classes, and
3
+ // every class has a default rule here, so the list looks finished out of the
4
+ // box and a project restyles it from its own CSS by the same names. The draft
5
+ // itself is the reply drafter's box (wb-reply-*, REPLY_STYLES in
6
+ // workbench-ai) when the app passes renderReplyBox. `npx workbench-ui styles`
7
+ // writes these into the project's public/styles/workbench.css inside
8
+ // `@layer workbench`. The names are public: renaming one is a breaking change.
9
+ const v = (name) => `var(--wb-nudge-${name})`;
10
+ const focus = { selector: ":focus-visible", about: "Has focus", css: `outline:none;box-shadow:0 0 0 3px ${v("focus")}` };
11
+ const button = `display:inline-flex;align-items:center;justify-content:center;min-height:2.75rem;padding:0 1rem;font:inherit;font-weight:600;border-radius:${v("radius")};cursor:pointer`;
12
+ /** The style hooks of the Waiting for you list (renderNudgeList). */
13
+ export const NUDGE_STYLES = {
14
+ format: 1,
15
+ tool: "nudge",
16
+ package: "@mccaskie-labs/workbench-nudges",
17
+ title: "Follow-up nudges",
18
+ prefix: "wb-nudge-",
19
+ variables: [
20
+ { name: "--wb-nudge-text", value: "#e8e8ec", about: "Text: the title, who it's for, the draft" },
21
+ { name: "--wb-nudge-muted", value: "#9a9aa6", about: "Quieter text: the step, the empty list" },
22
+ { name: "--wb-nudge-surface", value: "#1b1b1f", about: "Background of each nudge" },
23
+ { name: "--wb-nudge-sunk", value: "#141417", about: "Background of the list and the draft box" },
24
+ { name: "--wb-nudge-line", value: "#33333b", about: "Borders" },
25
+ { name: "--wb-nudge-due", value: "#d9822b", about: "The edge of a due nudge and its reason" },
26
+ { name: "--wb-nudge-taken", value: "#c9a227", about: "The edge of a nudge whose date was taken or has no draft" },
27
+ { name: "--wb-nudge-accent", value: "#4c8dff", about: "The main button: I sent it" },
28
+ { name: "--wb-nudge-on-accent", value: "#ffffff", about: "Text on the main button" },
29
+ { name: "--wb-nudge-focus", value: "rgba(76,141,255,.4)", about: "The ring round a control with focus" },
30
+ { name: "--wb-nudge-radius", value: "8px", about: "Corner rounding" },
31
+ ],
32
+ classes: [
33
+ { name: "wb-nudge-list", element: "section", about: "The whole Waiting for you list", css: `color:${v("text")};background:${v("sunk")};padding:.75rem;border-radius:${v("radius")}` },
34
+ { name: "wb-nudge-list-title", element: "h2", about: "\"Waiting for you\", with the count", css: "margin:0 0 .75rem;font-size:1.15rem;font-weight:600" },
35
+ { name: "wb-nudge-count", element: "span", about: "How many are waiting", css: `color:${v("muted")};font-weight:400` },
36
+ { name: "wb-nudge-empty", element: "p", about: "Nothing to follow up", css: `margin:0;color:${v("muted")}` },
37
+ { name: "wb-nudge-items", element: "ul", about: "The nudges", css: "list-style:none;margin:0;padding:0;display:grid;gap:.75rem" },
38
+ { name: "wb-nudge-item", element: "li", about: "One nudge's place in the list", css: "margin:0" },
39
+ {
40
+ name: "wb-nudge",
41
+ element: "article",
42
+ about: "One due follow-up",
43
+ css: `display:grid;gap:.5rem;padding:.75rem;color:${v("text")};background:${v("surface")};border:1px solid ${v("line")};border-left:4px solid ${v("due")};border-radius:${v("radius")}`,
44
+ },
45
+ { name: "wb-nudge-taken", element: "article", about: "A nudge whose date was taken, or with no draft (added to wb-nudge)", css: `border-left-color:${v("taken")}` },
46
+ { name: "wb-nudge-title", element: "h3", about: "Who and what it's about, from the app (Maria · Sat 12 Dec)", css: "margin:0;font-size:1rem;font-weight:600" },
47
+ { name: "wb-nudge-reason", element: "p", about: "\"No reply in 3 days\"", css: `margin:0;color:${v("due")};font-size:.9rem;font-weight:600` },
48
+ { name: "wb-nudge-step", element: "p", about: "\"Follow-up 1 of 2\"", css: `margin:0;color:${v("muted")};font-size:.85rem` },
49
+ { name: "wb-nudge-draft", element: "div", about: "The drafted follow-up: the reply drafter's box, or the plain text box", css: "min-width:0" },
50
+ {
51
+ name: "wb-nudge-text",
52
+ element: "textarea",
53
+ about: "The draft to copy, when the app doesn't pass the reply drafter's box",
54
+ css: `box-sizing:border-box;width:100%;padding:.75rem;font:inherit;line-height:1.45;color:${v("text")};background:${v("sunk")};border:1px solid ${v("line")};border-radius:${v("radius")};resize:vertical`,
55
+ states: [focus],
56
+ },
57
+ { name: "wb-nudge-none", element: "p", about: "No draft for this one", css: `margin:0;color:${v("muted")};font-size:.9rem` },
58
+ { name: "wb-nudge-actions", element: "div", about: "The nudge's buttons", css: "display:flex;flex-wrap:wrap;gap:.5rem;align-items:center" },
59
+ { name: "wb-nudge-form", element: "form", about: "One button's form", css: "display:contents" },
60
+ {
61
+ name: "wb-nudge-sent",
62
+ element: "button",
63
+ about: "I sent it: the follow-up went, so the next step counts from now",
64
+ css: `${button};color:${v("on-accent")};background:${v("accent")};border:1px solid ${v("accent")}`,
65
+ states: [focus],
66
+ },
67
+ { name: "wb-nudge-snooze", element: "button", about: "Remind me tomorrow", css: `${button};color:${v("text")};background:transparent;border:1px solid ${v("line")}`, states: [focus] },
68
+ { name: "wb-nudge-dismiss", element: "button", about: "Not needed", css: `${button};color:${v("muted")};background:transparent;border:1px solid transparent`, states: [focus] },
69
+ ],
70
+ };
package/dist/time.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ /** A duration in minutes, or null when it isn't one ("3d", "12h", "30m"). */
2
+ export declare function durationMinutes(text: unknown): number | null;
3
+ /** "21:00" in minutes after midnight, or null. */
4
+ export declare function clockMinutes(text: unknown): number | null;
5
+ export declare function validZone(tz: unknown): boolean;
6
+ /** `at` plus a duration: days on the local clock, minutes and hours as elapsed time. */
7
+ export declare function addDuration(at: Date, duration: string, timeZone: string): Date;
8
+ /** `at`, or the end of the quiet hours when `at` falls inside them. */
9
+ export declare function outOfQuiet(at: Date, quiet: {
10
+ from: string;
11
+ to: string;
12
+ } | undefined, timeZone: string): Date;
13
+ /** Today in the zone, YYYY-MM-DD. */
14
+ export declare function todayIn(timeZone: string, at: Date): string;
15
+ /** Minutes after local midnight at `at`. */
16
+ export declare function minutesIn(timeZone: string, at: Date): number;
17
+ /** A duration for people: "3 days", "1 day", "12 hours", "30 minutes". */
18
+ export declare function durationWords(duration: string): string;