@startsimpli/integrations 0.2.118 → 0.2.119
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@startsimpli/integrations",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.119",
|
|
4
4
|
"description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://startsimpli.com",
|
|
@@ -50,9 +50,9 @@
|
|
|
50
50
|
"react-native": ">=0.74.0",
|
|
51
51
|
"@startsimpli/ui-native": ">=0.1.12",
|
|
52
52
|
"react-native-safe-area-context": ">=4.0.0",
|
|
53
|
+
"@startsimpli/ui": "^0.4.171",
|
|
53
54
|
"@startsimpli/auth": "^0.4.50",
|
|
54
|
-
"@startsimpli/utils": "^0.4.17"
|
|
55
|
-
"@startsimpli/ui": "^0.4.171"
|
|
55
|
+
"@startsimpli/utils": "^0.4.17"
|
|
56
56
|
},
|
|
57
57
|
"peerDependenciesMeta": {
|
|
58
58
|
"react": {
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
composeBriefing, speakCount, speakDate, writeBriefingScript,
|
|
5
|
+
type BriefingItem, type BriefingScriptLlm,
|
|
6
|
+
} from '../corpus/briefing';
|
|
7
|
+
|
|
8
|
+
const ME = 'me';
|
|
9
|
+
const NOW = Date.parse('2026-11-05T14:00:00Z'); // Thursday 9:00 in New York
|
|
10
|
+
const TZ = 'America/New_York';
|
|
11
|
+
const item = (over: Partial<BriefingItem> & { id: string }): BriefingItem => ({
|
|
12
|
+
title: `Do ${over.id}`, status: 'open', ownerSub: ME, dueAt: '2026-11-05', ...over,
|
|
13
|
+
});
|
|
14
|
+
const brief = (items: BriefingItem[], max?: number) =>
|
|
15
|
+
composeBriefing(items, { ownerSub: ME, now: NOW, timeZone: TZ, maxItems: max });
|
|
16
|
+
const opts = { now: NOW, timeZone: TZ, name: 'Quinn' };
|
|
17
|
+
|
|
18
|
+
const day = [
|
|
19
|
+
item({ id: 'a', title: 'Review the **invoice** [LIN-123](https://linear.app/x/issue/LIN-123)', dueAt: '2026-11-02', linearIdentifier: 'LIN-123', priority: 1, focusName: 'Tandem' }),
|
|
20
|
+
item({ id: 'b', title: 'Finish briefing slice', status: 'in_progress', dueAt: null }),
|
|
21
|
+
item({ id: 'c', title: 'Ship the speech package' }),
|
|
22
|
+
];
|
|
23
|
+
const briefing = () => brief(day);
|
|
24
|
+
|
|
25
|
+
/** A fake model that returns the JSON contract for whatever items it was shown. */
|
|
26
|
+
const goodLlm = (extra: object = {}): BriefingScriptLlm => ({
|
|
27
|
+
write: vi.fn(async ({ prompt }) => {
|
|
28
|
+
const ids = [...prompt.matchAll(/\[id:([^\]]+)\]/g)].map((m) => m[1]);
|
|
29
|
+
return JSON.stringify({ lead: 'A steady one today.', items: ids.map((id) => ({ id, say: `Item ${id} needs you.` })), ...extra });
|
|
30
|
+
}),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe('speakDate / speakCount', () => {
|
|
34
|
+
it.each([
|
|
35
|
+
// The bead's example (2026-11-07 = Friday) was wrong: that day is a Saturday.
|
|
36
|
+
['2026-11-07', 'Saturday the seventh'],
|
|
37
|
+
['2026-11-06', 'Friday the sixth'],
|
|
38
|
+
['2026-11-05', 'Thursday the fifth'],
|
|
39
|
+
['2026-11-02', 'Monday the second'],
|
|
40
|
+
['2026-11-21', 'Saturday the twenty-first'],
|
|
41
|
+
['2026-11-30', 'Monday the thirtieth'],
|
|
42
|
+
['2026-10-30', 'Friday the thirtieth of October'],
|
|
43
|
+
])('%s -> %s', (iso, spoken) => expect(speakDate(iso, '2026-11-05')).toBe(spoken));
|
|
44
|
+
it.each([[1, 'one'], [2, 'two'], [8, 'eight'], [12, 'twelve'], [21, 'twenty-one'], [100, '100']])('%i -> %s', (n, w) =>
|
|
45
|
+
expect(speakCount(n)).toBe(w));
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
describe('writeBriefingScript', () => {
|
|
49
|
+
it('has no markdown, bullets, urls or identifiers read as codes (LIN-123 is not spoken)', async () => {
|
|
50
|
+
for (const llm of [goodLlm(), { write: async () => { throw new Error('down'); } }]) {
|
|
51
|
+
const s = await writeBriefingScript(briefing(), llm, opts);
|
|
52
|
+
expect(s.text).not.toMatch(/[*_#`\[\]]|https?:|www\.|^\s*[-•]|LIN-\d+|\b[A-Z]{2,}-\d+\b/m);
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('speaks dates and counts in words', async () => {
|
|
57
|
+
const s = await writeBriefingScript(briefing(), null, opts);
|
|
58
|
+
expect(s.text).toContain('Monday the second');
|
|
59
|
+
expect(s.text).toMatch(/\bthree items\b/);
|
|
60
|
+
expect(s.text).not.toMatch(/\d/);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('stays under 220 words even for a long model reply', async () => {
|
|
64
|
+
const wordy: BriefingScriptLlm = { write: async () => JSON.stringify({ lead: 'x', items: [{ id: 'a', say: 'word '.repeat(400) }, { id: 'b', say: 'ok' }, { id: 'c', say: 'ok' }] }) };
|
|
65
|
+
const s = await writeBriefingScript(briefing(), wordy, opts);
|
|
66
|
+
expect(s.words).toBeLessThanOrEqual(220);
|
|
67
|
+
expect(s.source).toBe('template'); // an over-budget reply is not trusted
|
|
68
|
+
const full = await writeBriefingScript(brief(Array.from({ length: 12 }, (_, n) => item({ id: `i${n}`, title: 'Review the quarterly vendor contract renewal terms with legal' }))), null, opts);
|
|
69
|
+
expect(full.words).toBeLessThanOrEqual(220);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it('greets in the second person with the part of day in the listener zone', async () => {
|
|
73
|
+
expect((await writeBriefingScript(briefing(), goodLlm(), opts)).text).toMatch(/^Good morning, Quinn\./);
|
|
74
|
+
const noon = { ...opts, now: Date.parse('2026-11-05T19:30:00Z') }; // 2:30pm NY
|
|
75
|
+
expect((await writeBriefingScript(composeBriefing(day, { ownerSub: ME, now: noon.now, timeZone: TZ }), null, noon)).text).toMatch(/^Good afternoon, Quinn\./);
|
|
76
|
+
const eve = { ...opts, now: Date.parse('2026-11-06T00:30:00Z') }; // 7:30pm NY, still the 5th
|
|
77
|
+
expect((await writeBriefingScript(composeBriefing(day, { ownerSub: ME, now: eve.now, timeZone: TZ }), null, eve)).text).toMatch(/^Good evening, Quinn\./);
|
|
78
|
+
expect((await writeBriefingScript(briefing(), null, { ...opts, name: undefined })).text).toMatch(/^Good morning\./);
|
|
79
|
+
expect((await writeBriefingScript(briefing(), null, opts)).text).toMatch(/\byou\b/i);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it.each([
|
|
83
|
+
['throws', { write: async () => { throw new Error('boom'); } }],
|
|
84
|
+
['times out', { write: () => new Promise<string>(() => {}) }],
|
|
85
|
+
['returns garbage', { write: async () => 'Sure! Here is your briefing: ...' }],
|
|
86
|
+
['returns markdown', { write: async () => JSON.stringify({ items: [{ id: 'a', say: '**bold**' }, { id: 'b', say: 'ok' }, { id: 'c', say: 'ok' }] }) }],
|
|
87
|
+
])('falls back to the template with the same items when the model %s', async (_n, llm) => {
|
|
88
|
+
const s = await writeBriefingScript(briefing(), llm as BriefingScriptLlm, { ...opts, timeoutMs: 20 });
|
|
89
|
+
expect(s.source).toBe('template');
|
|
90
|
+
expect(s.segments.filter((x) => x.id).map((x) => x.id)).toEqual(['a', 'b', 'c']);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('cannot add, drop, duplicate or reorder items', async () => {
|
|
94
|
+
const extra = goodLlm({ items: [{ id: 'a', say: 'x' }, { id: 'ghost', say: 'a made up task' }, { id: 'b', say: 'x' }, { id: 'c', say: 'x' }] });
|
|
95
|
+
const s1 = await writeBriefingScript(briefing(), extra, opts);
|
|
96
|
+
expect(s1.source).toBe('template');
|
|
97
|
+
expect(s1.text).not.toContain('made up');
|
|
98
|
+
const dropped = goodLlm({ items: [{ id: 'a', say: 'x' }] });
|
|
99
|
+
expect((await writeBriefingScript(briefing(), dropped, opts)).source).toBe('template');
|
|
100
|
+
const dup = goodLlm({ items: [{ id: 'a', say: 'x' }, { id: 'a', say: 'x' }, { id: 'c', say: 'x' }] });
|
|
101
|
+
expect((await writeBriefingScript(briefing(), dup, opts)).source).toBe('template');
|
|
102
|
+
// A reordered reply is kept but laid out in the composer's order: overdue still first.
|
|
103
|
+
const swapped = goodLlm({ items: [{ id: 'c', say: 'x' }, { id: 'b', say: 'x' }, { id: 'a', say: 'x' }] });
|
|
104
|
+
const reordered = await writeBriefingScript(briefing(), swapped, opts);
|
|
105
|
+
expect(reordered.source).toBe('llm');
|
|
106
|
+
expect(reordered.segments.filter((x) => x.id).map((x) => x.id)).toEqual(['a', 'b', 'c']);
|
|
107
|
+
const ok = await writeBriefingScript(briefing(), goodLlm(), opts);
|
|
108
|
+
expect(ok.source).toBe('llm');
|
|
109
|
+
expect(ok.segments.filter((x) => x.id).map((x) => x.id)).toEqual(['a', 'b', 'c']);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it('calls out overdue items first', async () => {
|
|
113
|
+
for (const llm of [null, goodLlm()]) {
|
|
114
|
+
const s = await writeBriefingScript(briefing(), llm, opts);
|
|
115
|
+
expect(s.segments.find((x) => x.id)!.id).toBe('a');
|
|
116
|
+
}
|
|
117
|
+
const t = await writeBriefingScript(briefing(), null, opts);
|
|
118
|
+
expect(t.text.indexOf('overdue')).toBeGreaterThan(-1);
|
|
119
|
+
expect(t.text.indexOf('overdue')).toBeLessThan(t.text.indexOf('Finish briefing slice'));
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it('records where each item starts and ends in the text (for voice replies)', async () => {
|
|
123
|
+
const s = await writeBriefingScript(briefing(), goodLlm(), opts);
|
|
124
|
+
for (const seg of s.segments.filter((x) => x.id)) {
|
|
125
|
+
expect(seg.start).toBeLessThan(seg.end);
|
|
126
|
+
expect(s.text.slice(seg.start, seg.end)).toContain(`Item ${seg.id} needs you.`);
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('says "and N more" when the composer capped the list', async () => {
|
|
131
|
+
const many = brief(Array.from({ length: 5 }, (_, n) => item({ id: `i${n}`, priority: n })), 3);
|
|
132
|
+
const s = await writeBriefingScript(many, null, opts);
|
|
133
|
+
expect(s.text).toMatch(/and two more/i);
|
|
134
|
+
expect((await writeBriefingScript(many, goodLlm(), opts)).text).toMatch(/and two more/i);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it('has a plain script for an empty day, and never calls the model', async () => {
|
|
138
|
+
const llm = goodLlm();
|
|
139
|
+
const s = await writeBriefingScript(brief([]), llm, opts);
|
|
140
|
+
expect(s.text).toMatch(/^Good morning, Quinn\. Nothing is due today/);
|
|
141
|
+
expect(s.segments).toEqual([]);
|
|
142
|
+
expect(llm.write).not.toHaveBeenCalled();
|
|
143
|
+
});
|
|
144
|
+
});
|
|
@@ -2,3 +2,6 @@ export { composeBriefing, localDate } from './compose';
|
|
|
2
2
|
export type {
|
|
3
3
|
Briefing, BriefingContext, BriefingEntry, BriefingItem, BriefingKind, BriefingOptions,
|
|
4
4
|
} from './types';
|
|
5
|
+
export { writeBriefingScript, templateScript, scriptPrompt, scriptSystemPrompt } from './script';
|
|
6
|
+
export type { BriefingScript, BriefingScriptLlm, BriefingScriptOptions, ScriptSegment } from './script';
|
|
7
|
+
export { speakCount, speakDate, speakable, isUnspeakable, partOfDay, wordCount } from './speak';
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SERVER-ONLY: the real model behind `BriefingScriptLlm`. Re-exported from
|
|
3
|
+
* `@startsimpli/integrations/corpus-llm` and never from the package index, for
|
|
4
|
+
* the reason `corpus/llm.ts` gives (no provider client in a browser bundle).
|
|
5
|
+
*/
|
|
6
|
+
import { LLMService } from '@startsimpli/llm';
|
|
7
|
+
|
|
8
|
+
import { voiceAnalyzerDefaults, type CorpusLlmOptions } from '../llm';
|
|
9
|
+
import type { BriefingScriptLlm } from './script';
|
|
10
|
+
|
|
11
|
+
export function createBriefingScriptLlm(options: CorpusLlmOptions = {}): BriefingScriptLlm {
|
|
12
|
+
const defaults = voiceAnalyzerDefaults(options.env, options);
|
|
13
|
+
const service =
|
|
14
|
+
options.service ??
|
|
15
|
+
new LLMService<unknown>({
|
|
16
|
+
preferredProvider: defaults.preferredProvider,
|
|
17
|
+
defaultModel: defaults.model,
|
|
18
|
+
// A little warmth: this is wording, not extraction. The validator holds the facts.
|
|
19
|
+
defaultTemperature: options.temperature ?? 0.5,
|
|
20
|
+
defaultMaxTokens: options.maxTokens ?? 900,
|
|
21
|
+
});
|
|
22
|
+
return {
|
|
23
|
+
async write({ system, prompt, timeoutMs }) {
|
|
24
|
+
if (!service.isAvailable()) throw new Error('No LLM provider is reachable for the briefing script.');
|
|
25
|
+
const response = await service.chat(prompt, system, { timeout: timeoutMs ?? options.timeoutMs });
|
|
26
|
+
return response.content;
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE SPOKEN SCRIPT (bd startsim-e8upb): turn a composed briefing into a short
|
|
3
|
+
* thing a person can listen to, and NEVER fail to produce one.
|
|
4
|
+
*
|
|
5
|
+
* THE MODEL ONLY WORDS THE ITEMS. The greeting, the counts, the "and N more" and
|
|
6
|
+
* the sign-off are ours, and the model's reply is a JSON list keyed by the item
|
|
7
|
+
* ids it was shown. So it cannot add a task (an unknown id fails), drop one,
|
|
8
|
+
* reorder them (we lay the text out in our order), or push the script over budget, and every sentence maps to an id
|
|
9
|
+
* - which is what lets a voice reply resolve "this one" by character offset.
|
|
10
|
+
* Anything off the contract (timeout, error, garbage, markup, a code like
|
|
11
|
+
* LIN-123, a numeric date, too long) is discarded for the deterministic template
|
|
12
|
+
* over the SAME items.
|
|
13
|
+
*/
|
|
14
|
+
import { partOfDay, isUnspeakable, speakCount, speakDate, speakable, wordCount } from './speak';
|
|
15
|
+
import type { Briefing, BriefingEntry } from './types';
|
|
16
|
+
|
|
17
|
+
/** One text completion. Server adapters wrap `@startsimpli/llm`; tests pass a fake. */
|
|
18
|
+
export interface BriefingScriptLlm {
|
|
19
|
+
write(input: { system: string; prompt: string; timeoutMs?: number }): Promise<string>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface BriefingScriptOptions {
|
|
23
|
+
now: number;
|
|
24
|
+
timeZone?: string;
|
|
25
|
+
/** How to address the listener. */
|
|
26
|
+
name?: string;
|
|
27
|
+
/** Model deadline; past it the template is used. Default 12 s. */
|
|
28
|
+
timeoutMs?: number;
|
|
29
|
+
/** Word budget (about 90 seconds spoken). Default 220. */
|
|
30
|
+
maxWords?: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ScriptSegment {
|
|
34
|
+
/** The item this stretch of text is about; null for greeting, lead and sign-off. */
|
|
35
|
+
id: string | null;
|
|
36
|
+
/** Offsets into `text`, end exclusive. */
|
|
37
|
+
start: number;
|
|
38
|
+
end: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface BriefingScript {
|
|
42
|
+
text: string;
|
|
43
|
+
segments: ScriptSegment[];
|
|
44
|
+
source: 'llm' | 'template';
|
|
45
|
+
words: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const DEFAULT_TIMEOUT_MS = 12_000;
|
|
49
|
+
const DEFAULT_MAX_WORDS = 220;
|
|
50
|
+
const MAX_LEAD_WORDS = 25;
|
|
51
|
+
const MAX_SAY_WORDS = 30;
|
|
52
|
+
|
|
53
|
+
export function scriptSystemPrompt(): string {
|
|
54
|
+
return [
|
|
55
|
+
'You write short spoken to-do briefings that a text-to-speech voice will read aloud.',
|
|
56
|
+
'Reply with ONLY a JSON object: {"lead": string, "items": [{"id": string, "say": string}]}.',
|
|
57
|
+
'"items" must contain EVERY item shown, exactly once, using the id given in [id:...]; do not add items.',
|
|
58
|
+
'"say" is one short, natural sentence about that item (at most 25 words), in the second person where it fits.',
|
|
59
|
+
'"lead" is one optional sentence (at most 20 words) setting the tone; use an empty string if nothing to add.',
|
|
60
|
+
'Plain spoken English only: no markdown, bullets, quotes, links, ticket codes like ABC-123, or digits for dates.',
|
|
61
|
+
'Say dates the way a person would (Friday the seventh). Never invent items, dates or details.',
|
|
62
|
+
].join('\n');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function itemLine(entry: BriefingEntry, today: string): string {
|
|
66
|
+
const title = speakable(entry.title) || 'an untitled item';
|
|
67
|
+
const when = entry.kind === 'overdue' && entry.dueDate ? `overdue, was due ${speakDate(entry.dueDate, today)}`
|
|
68
|
+
: entry.kind === 'in_progress' ? 'in progress'
|
|
69
|
+
: 'due today';
|
|
70
|
+
const project = entry.group === 'Personal' ? '' : `; project: ${speakable(entry.group, 6)}`;
|
|
71
|
+
return `[id:${entry.id}] ${title} (${when}${project})`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function scriptPrompt(briefing: Briefing): string {
|
|
75
|
+
const today = briefing.context.localDate;
|
|
76
|
+
return ['Items, most urgent first:', ...briefing.items.map((e) => itemLine(e, today))].join('\n');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// -- the deterministic template ----------------------------------------------
|
|
80
|
+
|
|
81
|
+
const projectOf = (e: BriefingEntry) => (e.group === 'Personal' ? '' : ` for ${speakable(e.group, 6)}`);
|
|
82
|
+
|
|
83
|
+
function templateSay(entry: BriefingEntry, today: string): string {
|
|
84
|
+
const title = speakable(entry.title) || 'An untitled item';
|
|
85
|
+
const lowered = title.charAt(0).toUpperCase() + title.slice(1);
|
|
86
|
+
if (entry.kind === 'overdue') {
|
|
87
|
+
return entry.dueDate
|
|
88
|
+
? `${lowered}${projectOf(entry)} is overdue, it was due ${speakDate(entry.dueDate, today)}.`
|
|
89
|
+
: `${lowered}${projectOf(entry)} is overdue.`;
|
|
90
|
+
}
|
|
91
|
+
if (entry.kind === 'in_progress') return `You are working on ${title}${projectOf(entry)}.`;
|
|
92
|
+
return `${lowered}${projectOf(entry)} is due today.`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function greeting(options: BriefingScriptOptions): string {
|
|
96
|
+
const part = partOfDay(options.now, options.timeZone ?? 'UTC');
|
|
97
|
+
return options.name ? `Good ${part}, ${options.name}.` : `Good ${part}.`;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function summaryLine(briefing: Briefing): string {
|
|
101
|
+
const n = briefing.total;
|
|
102
|
+
const noun = n === 1 ? 'item' : 'items';
|
|
103
|
+
const overdue = briefing.counts.overdue;
|
|
104
|
+
const tail = overdue > 0 ? `, ${speakCount(overdue)} of them overdue` : '';
|
|
105
|
+
return `You have ${speakCount(n)} ${noun} on your plate today${tail}.`;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function signOff(briefing: Briefing): string {
|
|
109
|
+
const n = briefing.remaining;
|
|
110
|
+
return n > 0 ? `And ${speakCount(n)} more after that.` : 'That is everything.';
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
interface Parts { lead?: string; says: Array<{ id: string; text: string }> }
|
|
114
|
+
|
|
115
|
+
/** Join the parts into one text, recording each item's offsets. */
|
|
116
|
+
function assemble(briefing: Briefing, options: BriefingScriptOptions, parts: Parts, source: 'llm' | 'template'): BriefingScript {
|
|
117
|
+
let text = '';
|
|
118
|
+
const segments: ScriptSegment[] = [];
|
|
119
|
+
const add = (piece: string, id: string | null) => {
|
|
120
|
+
if (text) text += ' ';
|
|
121
|
+
const start = text.length;
|
|
122
|
+
text += piece;
|
|
123
|
+
segments.push({ id, start, end: text.length });
|
|
124
|
+
};
|
|
125
|
+
add(greeting(options), null);
|
|
126
|
+
add(summaryLine(briefing), null);
|
|
127
|
+
if (parts.lead) add(parts.lead, null);
|
|
128
|
+
for (const say of parts.says) add(say.text, say.id);
|
|
129
|
+
add(signOff(briefing), null);
|
|
130
|
+
return { text, segments, source, words: wordCount(text) };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The template, shrunk (trailing items fold into "and N more") until it fits the budget. */
|
|
134
|
+
export function templateScript(briefing: Briefing, options: BriefingScriptOptions): BriefingScript {
|
|
135
|
+
const budget = options.maxWords ?? DEFAULT_MAX_WORDS;
|
|
136
|
+
const today = briefing.context.localDate;
|
|
137
|
+
let shown = briefing.items;
|
|
138
|
+
for (;;) {
|
|
139
|
+
const trimmed: Briefing = { ...briefing, items: shown, remaining: briefing.remaining + (briefing.items.length - shown.length) };
|
|
140
|
+
const built = assemble(trimmed, options, { says: shown.map((e) => ({ id: e.id, text: templateSay(e, today) })) }, 'template');
|
|
141
|
+
if (built.words <= budget || shown.length <= 1) return built;
|
|
142
|
+
shown = shown.slice(0, -1);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// -- the model path -----------------------------------------------------------
|
|
147
|
+
|
|
148
|
+
function emptyScript(options: BriefingScriptOptions): BriefingScript {
|
|
149
|
+
const text = `${greeting(options)} Nothing is due today, and nothing is overdue. Enjoy the clear day.`;
|
|
150
|
+
return { text, segments: [], source: 'template', words: wordCount(text) };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The model's reply as parts, or null when it is not exactly what was asked for. */
|
|
154
|
+
function parseReply(raw: string, briefing: Briefing): Parts | null {
|
|
155
|
+
let json: unknown;
|
|
156
|
+
try {
|
|
157
|
+
json = JSON.parse(raw.trim().replace(/^```(?:json)?\s*|\s*```$/g, ''));
|
|
158
|
+
} catch {
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
if (!json || typeof json !== 'object') return null;
|
|
162
|
+
const { lead, items } = json as { lead?: unknown; items?: unknown };
|
|
163
|
+
if (!Array.isArray(items) || items.length !== briefing.items.length) return null;
|
|
164
|
+
// Any order is fine (the model often groups by urgency): the ids must be EXACTLY the
|
|
165
|
+
// ones shown, each once, and the text is laid out in OUR order, so a reordered reply
|
|
166
|
+
// cannot change what is read first.
|
|
167
|
+
const byId = new Map<string, string>();
|
|
168
|
+
for (const raw of items) {
|
|
169
|
+
const row = raw as { id?: unknown; say?: unknown };
|
|
170
|
+
if (!row || typeof row.id !== 'string' || typeof row.say !== 'string' || byId.has(row.id)) return null;
|
|
171
|
+
const text = row.say.trim();
|
|
172
|
+
if (!text || wordCount(text) > MAX_SAY_WORDS || isUnspeakable(text)) return null;
|
|
173
|
+
byId.set(row.id, text);
|
|
174
|
+
}
|
|
175
|
+
const says: Parts['says'] = [];
|
|
176
|
+
for (const entry of briefing.items) {
|
|
177
|
+
const text = byId.get(entry.id);
|
|
178
|
+
if (text === undefined) return null;
|
|
179
|
+
says.push({ id: entry.id, text });
|
|
180
|
+
}
|
|
181
|
+
let leadText = '';
|
|
182
|
+
if (lead !== undefined && lead !== null && lead !== '') {
|
|
183
|
+
if (typeof lead !== 'string') return null;
|
|
184
|
+
leadText = lead.trim();
|
|
185
|
+
if (wordCount(leadText) > MAX_LEAD_WORDS || isUnspeakable(leadText)) return null;
|
|
186
|
+
}
|
|
187
|
+
return { lead: leadText || undefined, says };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {
|
|
191
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
192
|
+
const timeout = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error('briefing script timed out')), ms); });
|
|
193
|
+
return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* The script for a briefing. `llm` may be null (template only). Never throws:
|
|
198
|
+
* every failure of the model path ends in the template over the same items.
|
|
199
|
+
*/
|
|
200
|
+
export async function writeBriefingScript(
|
|
201
|
+
briefing: Briefing,
|
|
202
|
+
llm: BriefingScriptLlm | null,
|
|
203
|
+
options: BriefingScriptOptions,
|
|
204
|
+
): Promise<BriefingScript> {
|
|
205
|
+
if (briefing.empty) return emptyScript(options);
|
|
206
|
+
if (llm) {
|
|
207
|
+
const ms = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
208
|
+
try {
|
|
209
|
+
const raw = await withDeadline(
|
|
210
|
+
Promise.resolve(llm.write({ system: scriptSystemPrompt(), prompt: scriptPrompt(briefing), timeoutMs: ms })),
|
|
211
|
+
ms,
|
|
212
|
+
);
|
|
213
|
+
const parts = parseReply(raw, briefing);
|
|
214
|
+
if (parts) {
|
|
215
|
+
const built = assemble(briefing, options, parts, 'llm');
|
|
216
|
+
if (built.words <= (options.maxWords ?? DEFAULT_MAX_WORDS)) return built;
|
|
217
|
+
}
|
|
218
|
+
} catch {
|
|
219
|
+
// fall through to the template
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return templateScript(briefing, options);
|
|
223
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spoken forms: numbers, dates, and text made safe to read aloud. Pure.
|
|
3
|
+
*/
|
|
4
|
+
const ONES = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve',
|
|
5
|
+
'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
|
|
6
|
+
const TENS = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
|
|
7
|
+
const ORD_ONES = ['', 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth',
|
|
8
|
+
'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth'];
|
|
9
|
+
const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
|
10
|
+
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
|
|
11
|
+
'November', 'December'];
|
|
12
|
+
|
|
13
|
+
/** 0..99 in words; anything larger stays digits (a count that big is not read out). */
|
|
14
|
+
export function speakCount(n: number): string {
|
|
15
|
+
if (n < 20) return ONES[n] ?? String(n);
|
|
16
|
+
if (n < 100) return TENS[Math.floor(n / 10)] + (n % 10 ? `-${ONES[n % 10]}` : '');
|
|
17
|
+
return String(n);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function ordinal(n: number): string {
|
|
21
|
+
if (n < 20) return ORD_ONES[n];
|
|
22
|
+
if (n % 10 === 0) return TENS[n / 10].replace(/y$/, 'ieth');
|
|
23
|
+
return `${TENS[Math.floor(n / 10)]}-${ORD_ONES[n % 10]}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* `2026-11-07` -> `Friday the seventh`; the month is added only when it is not
|
|
28
|
+
* the month of `today` (`Friday the thirtieth of October`).
|
|
29
|
+
*/
|
|
30
|
+
export function speakDate(isoDate: string, today: string): string {
|
|
31
|
+
const [y, m, d] = isoDate.split('-').map(Number);
|
|
32
|
+
const weekday = WEEKDAYS[new Date(Date.UTC(y, m - 1, d)).getUTCDay()];
|
|
33
|
+
const sameMonth = isoDate.slice(0, 7) === today.slice(0, 7);
|
|
34
|
+
return `${weekday} the ${ordinal(d)}${sameMonth ? '' : ` of ${MONTHS[m - 1]}`}`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Ticket-style codes (`LIN-123`) are never read out: spelled aloud they are noise. */
|
|
38
|
+
export const IDENTIFIER = /\b[A-Za-z]{2,10}-\d+\b/g;
|
|
39
|
+
const MARKDOWN = /[*_#`~<>|\\]|\[|\]|^\s*[-•>]\s/m;
|
|
40
|
+
const URL = /https?:\/\/|www\./i;
|
|
41
|
+
const NUMERIC_DATE = /\b\d{4}-\d{2}-\d{2}\b|\b\d{1,2}\/\d{1,2}(\/\d{2,4})?\b/;
|
|
42
|
+
|
|
43
|
+
/** True when `text` would sound wrong read aloud: markup, links, codes, numeric dates. */
|
|
44
|
+
export function isUnspeakable(text: string): boolean {
|
|
45
|
+
return MARKDOWN.test(text) || URL.test(text) || new RegExp(IDENTIFIER.source).test(text) || NUMERIC_DATE.test(text);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A title made speakable: markdown links keep their label, markup and codes go, whitespace collapses. */
|
|
49
|
+
export function speakable(text: string, maxWords = 14): string {
|
|
50
|
+
const words = text
|
|
51
|
+
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
|
|
52
|
+
.replace(/https?:\/\/\S+|www\.\S+/gi, 'a link')
|
|
53
|
+
.replace(IDENTIFIER, '')
|
|
54
|
+
.replace(/[*_#`~<>|\\[\]]/g, '')
|
|
55
|
+
.replace(/^\s*[-•>]\s+/gm, '')
|
|
56
|
+
.replace(/\s+/g, ' ')
|
|
57
|
+
.trim()
|
|
58
|
+
.replace(/\s+([,.;:!?])/g, '$1')
|
|
59
|
+
.split(' ')
|
|
60
|
+
.filter(Boolean);
|
|
61
|
+
const cut = words.slice(0, maxWords).join(' ').replace(/[,.;:]+$/, '');
|
|
62
|
+
return cut;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function wordCount(text: string): number {
|
|
66
|
+
return text.trim() ? text.trim().split(/\s+/).length : 0;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function partOfDay(instant: number, timeZone: string): 'morning' | 'afternoon' | 'evening' {
|
|
70
|
+
const hour = Number(new Intl.DateTimeFormat('en-US', { timeZone, hour: 'numeric', hourCycle: 'h23' }).format(new Date(instant)));
|
|
71
|
+
if (hour < 12) return 'morning';
|
|
72
|
+
return hour < 17 ? 'afternoon' : 'evening';
|
|
73
|
+
}
|