@startsimpli/integrations 0.2.118 → 0.2.120
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 +2 -2
- package/src/__tests__/briefing-route.test.ts +212 -0
- package/src/__tests__/briefing-script.test.ts +144 -0
- package/src/__tests__/briefing-voice-config.test.ts +40 -0
- package/src/corpus/briefing/cache-key.ts +28 -0
- package/src/corpus/briefing/generate.ts +159 -0
- package/src/corpus/briefing/index.ts +9 -0
- package/src/corpus/briefing/llm.ts +87 -0
- package/src/corpus/briefing/respond.ts +62 -0
- package/src/corpus/briefing/script.ts +223 -0
- package/src/corpus/briefing/speak.ts +73 -0
- package/src/corpus/briefing/store.ts +134 -0
- package/src/corpus/llm.ts +3 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@startsimpli/integrations",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.120",
|
|
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,8 +50,8 @@
|
|
|
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/auth": "^0.4.50",
|
|
54
53
|
"@startsimpli/utils": "^0.4.17",
|
|
54
|
+
"@startsimpli/auth": "^0.4.50",
|
|
55
55
|
"@startsimpli/ui": "^0.4.171"
|
|
56
56
|
},
|
|
57
57
|
"peerDependenciesMeta": {
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
briefingAudioResponse, createEntityBriefingStore, generateBriefing, briefingResponse,
|
|
5
|
+
type BriefingDeps, type BriefingItem, type BriefingScriptLlm,
|
|
6
|
+
} from '../corpus/briefing';
|
|
7
|
+
|
|
8
|
+
const NOW = Date.parse('2026-11-05T14:00:00Z');
|
|
9
|
+
const TZ = 'America/New_York';
|
|
10
|
+
const mk = (id: string, over: Partial<BriefingItem> = {}, owner = 'me'): BriefingItem =>
|
|
11
|
+
({ id, title: `Do ${id}`, status: 'open', ownerSub: owner, dueAt: '2026-11-05', priority: 2, ...over });
|
|
12
|
+
|
|
13
|
+
/** The tenant's entity verbs, in memory: shallow-merging upsert, lookup by external_id, owner scope by token. */
|
|
14
|
+
function fakeTenant(owner: string, shared: Map<string, any> = new Map()) {
|
|
15
|
+
let seq = shared.size;
|
|
16
|
+
return {
|
|
17
|
+
rows: shared,
|
|
18
|
+
http: {
|
|
19
|
+
get: vi.fn(async (path: string, options?: { params?: Record<string, unknown> }) => {
|
|
20
|
+
if (path.startsWith('api/v1/entities/')) {
|
|
21
|
+
const row = [...shared.values()].find((r) => String(r.id) === path.split('/').pop());
|
|
22
|
+
if (!row || row.owner_sub !== owner) throw Object.assign(new Error('nf'), { status: 404 });
|
|
23
|
+
return row;
|
|
24
|
+
}
|
|
25
|
+
const ext = String(options?.params?.external_id__in ?? '');
|
|
26
|
+
// org-wide read for this type on purpose: the store must not rely on row scope alone
|
|
27
|
+
return { results: [...shared.values()].filter((r) => r.external_id === ext) };
|
|
28
|
+
}),
|
|
29
|
+
post: vi.fn(async (_path: string, body: any) => {
|
|
30
|
+
const key = `${body.external_id}`;
|
|
31
|
+
const prev = shared.get(key);
|
|
32
|
+
const row = { id: prev?.id ?? ++seq, owner_sub: prev?.owner_sub ?? owner, ...prev, external_id: body.external_id, name: body.name, data: { ...(prev?.data ?? {}), ...body.data } };
|
|
33
|
+
shared.set(key, row);
|
|
34
|
+
return row;
|
|
35
|
+
}),
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function setup(items: BriefingItem[], over: Partial<BriefingDeps> = {}, owner = 'me', shared?: Map<string, any>) {
|
|
41
|
+
const tenant = fakeTenant(owner, shared);
|
|
42
|
+
const synthesize = vi.fn(async ({ text }: { text: string }) => ({
|
|
43
|
+
audio: new Uint8Array([1, 2, 3]), mimeType: 'audio/mpeg', model: 'm', provider: 'openai',
|
|
44
|
+
usage: { characters: text.length, costUsd: 0.001 },
|
|
45
|
+
}));
|
|
46
|
+
const llm: BriefingScriptLlm = {
|
|
47
|
+
write: vi.fn(async ({ prompt }) => {
|
|
48
|
+
const ids = [...prompt.matchAll(/\[id:([^\]]+)\]/g)].map((m) => m[1]);
|
|
49
|
+
return JSON.stringify({ lead: '', items: ids.map((id) => ({ id, say: `Handle ${id}.` })) });
|
|
50
|
+
}),
|
|
51
|
+
};
|
|
52
|
+
const put = vi.fn(async ({ noteId }: { noteId: string }) => `s3://voice-audio/voice/org/${noteId}.mp3`);
|
|
53
|
+
const url = vi.fn(async (ref: string, ttl: number) => `https://signed.example/${encodeURIComponent(ref)}?ttl=${ttl}`);
|
|
54
|
+
const currentItems = { list: items };
|
|
55
|
+
const deps: BriefingDeps = {
|
|
56
|
+
http: tenant.http as never,
|
|
57
|
+
orgId: 'org',
|
|
58
|
+
ownerSub: owner,
|
|
59
|
+
loadItems: async () => currentItems.list,
|
|
60
|
+
synthesize,
|
|
61
|
+
scriptLlm: llm,
|
|
62
|
+
audio: { put, url },
|
|
63
|
+
now: () => NOW,
|
|
64
|
+
timeZone: TZ,
|
|
65
|
+
name: 'Quinn',
|
|
66
|
+
...over,
|
|
67
|
+
};
|
|
68
|
+
return { deps, tenant, synthesize, llm, put, url, currentItems };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
describe('briefing route', () => {
|
|
72
|
+
it('returns text, audio url, items and a briefing id', async () => {
|
|
73
|
+
const { deps } = setup([mk('a'), mk('b', { priority: 1 })]);
|
|
74
|
+
const b = await generateBriefing(deps, {});
|
|
75
|
+
expect(b.briefingId).toBeTruthy();
|
|
76
|
+
expect(b.text).toMatch(/^Good morning, Quinn\./);
|
|
77
|
+
expect(b.audioUrl).toMatch(/^https:\/\/signed\.example\//);
|
|
78
|
+
expect(b.items.map((i) => i.id)).toEqual(['b', 'a']);
|
|
79
|
+
expect(b.cached).toBe(false);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('serves a second call the same day for the same set from cache: zero LLM, zero TTS', async () => {
|
|
83
|
+
const { deps, llm, synthesize } = setup([mk('a')]);
|
|
84
|
+
const first = await generateBriefing(deps, {});
|
|
85
|
+
const second = await generateBriefing(deps, {});
|
|
86
|
+
expect(second.cached).toBe(true);
|
|
87
|
+
expect(second.briefingId).toBe(first.briefingId);
|
|
88
|
+
expect(second.text).toBe(first.text);
|
|
89
|
+
expect(second.audioUrl).toBeTruthy();
|
|
90
|
+
expect(llm.write).toHaveBeenCalledTimes(1);
|
|
91
|
+
expect(synthesize).toHaveBeenCalledTimes(1);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it.each([
|
|
95
|
+
['title', (i: BriefingItem) => ({ ...i, title: 'Do a, renamed' })],
|
|
96
|
+
['status', (i: BriefingItem) => ({ ...i, status: 'in_progress' })],
|
|
97
|
+
['priority', (i: BriefingItem) => ({ ...i, priority: 0 })],
|
|
98
|
+
['due date', (i: BriefingItem) => ({ ...i, dueAt: '2026-11-04' })],
|
|
99
|
+
])('changing an item (%s) invalidates the cache and the next call regenerates', async (_n, change) => {
|
|
100
|
+
const { deps, llm, synthesize, currentItems } = setup([mk('a')]);
|
|
101
|
+
await generateBriefing(deps, {});
|
|
102
|
+
currentItems.list = [change(currentItems.list[0])];
|
|
103
|
+
const next = await generateBriefing(deps, {});
|
|
104
|
+
expect(next.cached).toBe(false);
|
|
105
|
+
expect(llm.write).toHaveBeenCalledTimes(2);
|
|
106
|
+
expect(synthesize).toHaveBeenCalledTimes(2);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('an item leaving or joining the set invalidates too', async () => {
|
|
110
|
+
const { deps, synthesize, currentItems } = setup([mk('a')]);
|
|
111
|
+
await generateBriefing(deps, {});
|
|
112
|
+
currentItems.list = [mk('a'), mk('b')];
|
|
113
|
+
expect((await generateBriefing(deps, {})).cached).toBe(false);
|
|
114
|
+
currentItems.list = [mk('a')];
|
|
115
|
+
expect((await generateBriefing(deps, {})).cached).toBe(false);
|
|
116
|
+
expect(synthesize).toHaveBeenCalledTimes(3);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it('force regenerates even when nothing changed', async () => {
|
|
120
|
+
const { deps, synthesize } = setup([mk('a')]);
|
|
121
|
+
await generateBriefing(deps, {});
|
|
122
|
+
const again = await generateBriefing(deps, { force: true });
|
|
123
|
+
expect(again.cached).toBe(false);
|
|
124
|
+
expect(synthesize).toHaveBeenCalledTimes(2);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it('a TTS failure returns the text with audio null and a reason, never an error', async () => {
|
|
128
|
+
const { deps } = setup([mk('a')], { synthesize: async () => { throw new Error('tts down'); } });
|
|
129
|
+
const b = await generateBriefing(deps, {});
|
|
130
|
+
expect(b.audioUrl).toBeNull();
|
|
131
|
+
expect(b.audioReason).toMatch(/tts down/);
|
|
132
|
+
expect(b.text).toContain('Handle a.');
|
|
133
|
+
const res = await briefingResponse(new Request('http://x/corpus/briefing', { method: 'POST', body: '{}' }), deps);
|
|
134
|
+
expect(res.status).toBe(200);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it('retries only the audio when the text is cached but the last synth failed (no second model call)', async () => {
|
|
138
|
+
let fail = true;
|
|
139
|
+
const { deps, llm, synthesize } = setup([mk('a')], {
|
|
140
|
+
synthesize: async ({ text }) => {
|
|
141
|
+
if (fail) throw new Error('tts down');
|
|
142
|
+
return { audio: new Uint8Array([9]), mimeType: 'audio/mpeg', model: 'm', provider: 'openai', usage: { characters: text.length } };
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
await generateBriefing(deps, {});
|
|
146
|
+
fail = false;
|
|
147
|
+
const healed = await generateBriefing(deps, {});
|
|
148
|
+
expect(healed.audioUrl).toBeTruthy();
|
|
149
|
+
expect(llm.write).toHaveBeenCalledTimes(1);
|
|
150
|
+
expect(synthesize).toBeDefined();
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it('is owner scoped: another user never gets this user\'s cached briefing', async () => {
|
|
154
|
+
const shared = new Map<string, any>();
|
|
155
|
+
const mine = setup([mk('a')], {}, 'me', shared);
|
|
156
|
+
const mineOut = await generateBriefing(mine.deps, {});
|
|
157
|
+
const theirs = setup([mk('a', {}, 'you')], {}, 'you', shared);
|
|
158
|
+
const theirOut = await generateBriefing(theirs.deps, {});
|
|
159
|
+
expect(theirOut.cached).toBe(false);
|
|
160
|
+
expect(theirOut.briefingId).not.toBe(mineOut.briefingId);
|
|
161
|
+
expect(theirs.synthesize).toHaveBeenCalledTimes(1);
|
|
162
|
+
// their rows are separate, and a row that is somehow readable is still refused when the owner differs
|
|
163
|
+
const store = createEntityBriefingStore(theirs.deps.http as never, 'you');
|
|
164
|
+
const stolen = await store.find(`briefing:2026-11-05:me`);
|
|
165
|
+
expect(stolen).toBeNull();
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
it('keeps the audio in the voice-audio store and asks for a short-lived url', async () => {
|
|
169
|
+
const { deps, put, url } = setup([mk('a')]);
|
|
170
|
+
const b = await generateBriefing(deps, {});
|
|
171
|
+
expect(put).toHaveBeenCalledTimes(1);
|
|
172
|
+
expect(put.mock.calls[0][0].mimeType).toBe('audio/mpeg');
|
|
173
|
+
const [, ttl] = url.mock.calls[0];
|
|
174
|
+
expect(ttl).toBeGreaterThan(0);
|
|
175
|
+
expect(ttl).toBeLessThanOrEqual(600);
|
|
176
|
+
expect(b.audioUrl).toContain('ttl=');
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it('persists the briefing context: ordered item ids and per-item character offsets', async () => {
|
|
180
|
+
const { deps, tenant } = setup([mk('a', { priority: 1 }), mk('b', { priority: 2 })]);
|
|
181
|
+
const b = await generateBriefing(deps, {});
|
|
182
|
+
const row = [...tenant.rows.values()][0];
|
|
183
|
+
const ctx = row.data.briefing_context;
|
|
184
|
+
expect(ctx.itemIds).toEqual(['a', 'b']);
|
|
185
|
+
expect(ctx.localDate).toBe('2026-11-05');
|
|
186
|
+
expect(ctx.offsets.map((o: any) => o.id)).toEqual(['a', 'b']);
|
|
187
|
+
for (const o of ctx.offsets) expect(b.text.slice(o.start, o.end)).toContain(`Handle ${o.id}.`);
|
|
188
|
+
expect(b.context.offsets).toEqual(ctx.offsets);
|
|
189
|
+
expect(row.data.source).toBe('briefing');
|
|
190
|
+
expect(row.data.body).toBeUndefined(); // the to-do extractor reads body/summary; a briefing must give it nothing
|
|
191
|
+
expect(row.data.summary).toBeUndefined();
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it('reads a stored briefing back (by id, owner only) for voice replies', async () => {
|
|
195
|
+
const { deps, tenant } = setup([mk('a')]);
|
|
196
|
+
const b = await generateBriefing(deps, {});
|
|
197
|
+
const res = await briefingAudioResponse(String(b.briefingId), { http: tenant.http as never, audio: { get: async () => ({ audio: new Uint8Array([1]), mimeType: 'audio/mpeg' }) } });
|
|
198
|
+
expect(res.status).toBe(200);
|
|
199
|
+
expect(res.headers.get('content-type')).toBe('audio/mpeg');
|
|
200
|
+
const other = fakeTenant('you', tenant.rows);
|
|
201
|
+
const denied = await briefingAudioResponse(String(b.briefingId), { http: other.http as never, audio: { get: async () => ({ audio: new Uint8Array([1]), mimeType: 'audio/mpeg' }) } });
|
|
202
|
+
expect(denied.status).toBe(404);
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it('an empty day is still a spoken briefing, with no model call', async () => {
|
|
206
|
+
const { deps, llm } = setup([]);
|
|
207
|
+
const b = await generateBriefing(deps, {});
|
|
208
|
+
expect(b.items).toEqual([]);
|
|
209
|
+
expect(b.text).toMatch(/Nothing is due today/);
|
|
210
|
+
expect(llm.write).not.toHaveBeenCalled();
|
|
211
|
+
});
|
|
212
|
+
});
|
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { briefingVoices, createBriefingSynthesizer } from '../corpus/briefing/llm';
|
|
4
|
+
|
|
5
|
+
const ok = (provider: string) => vi.fn(async (r: any) => ({ audio: new Uint8Array([1]), mimeType: 'audio/mpeg', model: 'm', provider, usage: { characters: r.text.length }, voiceId: r.voiceId }));
|
|
6
|
+
|
|
7
|
+
describe('briefing voice configuration', () => {
|
|
8
|
+
it('defaults to ElevenLabs ai_assistant on flash, OpenAI behind it', () => {
|
|
9
|
+
const v = briefingVoices({});
|
|
10
|
+
expect(v[0]).toMatchObject({ provider: 'elevenlabs', voiceId: 'xB7U4iivDiPcO06WZ47T', model: 'eleven_flash_v2_5', outputFormat: 'mp3_44100_128' });
|
|
11
|
+
expect(v[1]).toMatchObject({ provider: 'openai', voiceId: 'alloy' });
|
|
12
|
+
});
|
|
13
|
+
it('is overridden by env without code changes', () => {
|
|
14
|
+
const v = briefingVoices({ BRIEFING_TTS_VOICE_ID: 'abc', BRIEFING_TTS_MODEL: 'eleven_v3' });
|
|
15
|
+
expect(v[0]).toMatchObject({ provider: 'elevenlabs', voiceId: 'abc', model: 'eleven_v3' });
|
|
16
|
+
expect(briefingVoices({ BRIEFING_TTS_PROVIDER: 'openai' })[0]).toMatchObject({ provider: 'openai', voiceId: undefined });
|
|
17
|
+
});
|
|
18
|
+
it('uses the first available provider with that provider\'s own voice settings', async () => {
|
|
19
|
+
const el = { isAvailable: () => true, synthesize: ok('elevenlabs') };
|
|
20
|
+
const oa = { isAvailable: () => true, synthesize: ok('openai') };
|
|
21
|
+
const synth = createBriefingSynthesizer({ env: {}, serviceFor: (p) => (p === 'elevenlabs' ? el : oa) as never });
|
|
22
|
+
expect((await synth({ text: 'hi' })).provider).toBe('elevenlabs');
|
|
23
|
+
expect(el.synthesize).toHaveBeenCalledWith(expect.objectContaining({ voiceId: 'xB7U4iivDiPcO06WZ47T', model: 'eleven_flash_v2_5' }));
|
|
24
|
+
});
|
|
25
|
+
it('falls back to OpenAI, with OpenAI voice settings (never the ElevenLabs voice id), when ElevenLabs fails or has no key', async () => {
|
|
26
|
+
const down = { isAvailable: () => true, synthesize: vi.fn(async () => { throw new Error('quota'); }) };
|
|
27
|
+
const oa = { isAvailable: () => true, synthesize: ok('openai') };
|
|
28
|
+
const s1 = createBriefingSynthesizer({ env: {}, serviceFor: (p) => (p === 'elevenlabs' ? down : oa) as never });
|
|
29
|
+
expect((await s1({ text: 'hi' })).provider).toBe('openai');
|
|
30
|
+
expect(oa.synthesize).toHaveBeenCalledWith(expect.objectContaining({ voiceId: 'alloy', model: 'gpt-4o-mini-tts' }));
|
|
31
|
+
const nokey = { isAvailable: () => false, synthesize: vi.fn() };
|
|
32
|
+
const s2 = createBriefingSynthesizer({ env: {}, serviceFor: (p) => (p === 'elevenlabs' ? nokey : oa) as never });
|
|
33
|
+
expect((await s2({ text: 'hi' })).provider).toBe('openai');
|
|
34
|
+
expect(nokey.synthesize).not.toHaveBeenCalled();
|
|
35
|
+
});
|
|
36
|
+
it('throws the last error when nothing works', async () => {
|
|
37
|
+
const s = createBriefingSynthesizer({ env: {}, serviceFor: () => ({ isAvailable: () => true, synthesize: async () => { throw new Error('all down'); } }) as never });
|
|
38
|
+
await expect(s({ text: 'hi' })).rejects.toThrow('all down');
|
|
39
|
+
});
|
|
40
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Briefing } from './types';
|
|
2
|
+
|
|
3
|
+
/** Bump when the script wording or contract changes, so yesterday's cached script is not reused. */
|
|
4
|
+
export const SCRIPT_VERSION = 1;
|
|
5
|
+
|
|
6
|
+
/** 53-bit string hash (cyrb53). A cache key, not a security boundary, and it needs no `crypto`. */
|
|
7
|
+
export function hashString(text: string): string {
|
|
8
|
+
let h1 = 0xdeadbeef;
|
|
9
|
+
let h2 = 0x41c6ce57;
|
|
10
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
11
|
+
const ch = text.charCodeAt(i);
|
|
12
|
+
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
13
|
+
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
14
|
+
}
|
|
15
|
+
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
|
16
|
+
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
17
|
+
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Identity of what would be SAID: the ordered spoken items with the fields that
|
|
22
|
+
* change the wording, plus how many were left out. Any edit to one of them (or an
|
|
23
|
+
* item joining or leaving the set) changes it; an unrelated row does not.
|
|
24
|
+
*/
|
|
25
|
+
export function briefingContentHash(briefing: Briefing): string {
|
|
26
|
+
const parts = briefing.items.map((e) => [e.id, e.title, e.kind, e.group, e.dueDate ?? '', e.priority ?? ''].join('␟'));
|
|
27
|
+
return hashString([`v${SCRIPT_VERSION}`, briefing.context.localDate, briefing.remaining, ...parts].join('␞'));
|
|
28
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE BRIEFING ROUTE'S LOGIC (bd startsim-0mys4), Request-free so a Next route
|
|
3
|
+
* handler is a few lines and a Celery-free tenant or the native app can call it.
|
|
4
|
+
*
|
|
5
|
+
* load items -> compose -> hash -> (cache hit? serve it) -> script -> speak -> keep
|
|
6
|
+
*
|
|
7
|
+
* A REPEAT TAP COSTS NOTHING: one row per (owner, local day) holds the script, the
|
|
8
|
+
* audio reference and the content hash of what was said. Same hash = the stored
|
|
9
|
+
* row, zero model calls, zero synthesis. Any edit to a spoken item changes the
|
|
10
|
+
* hash, so the next tap regenerates (a voice edit is therefore visible in the next
|
|
11
|
+
* briefing). Text is ALWAYS returned; speech is best-effort: a synthesis failure
|
|
12
|
+
* answers 200 with `audioUrl: null` and a reason, and a later call retries just
|
|
13
|
+
* the audio from the stored text.
|
|
14
|
+
*/
|
|
15
|
+
import type { CorpusHttp } from '../client';
|
|
16
|
+
import { briefingContentHash } from './cache-key';
|
|
17
|
+
import { composeBriefing } from './compose';
|
|
18
|
+
import { writeBriefingScript, type BriefingScriptLlm } from './script';
|
|
19
|
+
import {
|
|
20
|
+
briefingExternalId, createEntityBriefingStore, offsetsOf,
|
|
21
|
+
type BriefingContextRecord, type BriefingRecord, type BriefingStore,
|
|
22
|
+
} from './store';
|
|
23
|
+
import type { BriefingEntry, BriefingItem } from './types';
|
|
24
|
+
|
|
25
|
+
/** The slice of `SpeechService.synthesize` this needs; tests pass a fake. */
|
|
26
|
+
export type BriefingSynthesize = (request: { text: string }) => Promise<{
|
|
27
|
+
audio: Uint8Array;
|
|
28
|
+
mimeType: string;
|
|
29
|
+
model: string;
|
|
30
|
+
provider: string;
|
|
31
|
+
usage: { characters?: number; costUsd?: number };
|
|
32
|
+
}>;
|
|
33
|
+
|
|
34
|
+
/** Audio bytes live in the workspace's voice-audio store; `url` turns a reference into a short-lived link. */
|
|
35
|
+
export interface BriefingAudio {
|
|
36
|
+
put(input: { noteId: string; audio: Uint8Array; mimeType: string }): Promise<string>;
|
|
37
|
+
url(audioRef: string, ttlSeconds: number): Promise<string>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface BriefingDeps {
|
|
41
|
+
http: Pick<CorpusHttp, 'get'> & { post<T>(path: string, body?: unknown): Promise<T> };
|
|
42
|
+
orgId: string;
|
|
43
|
+
/** The caller. Taken from the verified session, never from the request body. */
|
|
44
|
+
ownerSub: string;
|
|
45
|
+
/** The caller's open to-dos (any owner may be returned; the composer scopes to `ownerSub`). */
|
|
46
|
+
loadItems(): Promise<BriefingItem[]>;
|
|
47
|
+
synthesize: BriefingSynthesize;
|
|
48
|
+
scriptLlm: BriefingScriptLlm | null;
|
|
49
|
+
audio: BriefingAudio;
|
|
50
|
+
/** Override the default tenant-row store (tests, other backends). */
|
|
51
|
+
store?: BriefingStore;
|
|
52
|
+
now?: () => number;
|
|
53
|
+
/** IANA zone of the listener. */
|
|
54
|
+
timeZone?: string;
|
|
55
|
+
name?: string;
|
|
56
|
+
/** Seconds a signed audio link lives. Default 300. */
|
|
57
|
+
audioTtlSeconds?: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface BriefingRequest {
|
|
61
|
+
/** Regenerate even if the stored briefing is current. */
|
|
62
|
+
force?: boolean;
|
|
63
|
+
/** Overrides `deps.timeZone`. */
|
|
64
|
+
timeZone?: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface BriefingResult {
|
|
68
|
+
briefingId: string;
|
|
69
|
+
text: string;
|
|
70
|
+
audioUrl: string | null;
|
|
71
|
+
/** Why there is no audio, when there is none. */
|
|
72
|
+
audioReason?: string;
|
|
73
|
+
items: BriefingEntry[];
|
|
74
|
+
remaining: number;
|
|
75
|
+
context: BriefingContextRecord;
|
|
76
|
+
scriptSource: 'llm' | 'template';
|
|
77
|
+
cached: boolean;
|
|
78
|
+
/** Wall time this call spent, ms. */
|
|
79
|
+
ms: number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const DEFAULT_TTL = 300;
|
|
83
|
+
const reasonOf = (error: unknown) => (error instanceof Error ? error.message : String(error)).slice(0, 300);
|
|
84
|
+
|
|
85
|
+
export async function generateBriefing(deps: BriefingDeps, request: BriefingRequest): Promise<BriefingResult> {
|
|
86
|
+
const clock = deps.now ?? Date.now;
|
|
87
|
+
const started = Date.now();
|
|
88
|
+
const timeZone = request.timeZone ?? deps.timeZone ?? 'UTC';
|
|
89
|
+
const now = clock();
|
|
90
|
+
const ttl = Math.min(deps.audioTtlSeconds ?? DEFAULT_TTL, 600);
|
|
91
|
+
const store = deps.store ?? createEntityBriefingStore(deps.http, deps.ownerSub);
|
|
92
|
+
|
|
93
|
+
const briefing = composeBriefing(await deps.loadItems(), { ownerSub: deps.ownerSub, now, timeZone });
|
|
94
|
+
const hash = briefingContentHash(briefing);
|
|
95
|
+
const externalId = briefingExternalId(deps.ownerSub, briefing.context.localDate);
|
|
96
|
+
const stored = request.force ? null : await store.find(externalId);
|
|
97
|
+
const current = stored && stored.contentHash === hash ? stored : null;
|
|
98
|
+
|
|
99
|
+
const linkFor = async (ref: string | undefined): Promise<string | null> => {
|
|
100
|
+
if (!ref) return null;
|
|
101
|
+
try { return await deps.audio.url(ref, ttl); } catch { return null; }
|
|
102
|
+
};
|
|
103
|
+
const result = (record: BriefingRecord, audioUrl: string | null, cached: boolean, reason?: string): BriefingResult => ({
|
|
104
|
+
briefingId: record.id,
|
|
105
|
+
text: record.text,
|
|
106
|
+
audioUrl,
|
|
107
|
+
...(audioUrl ? {} : { audioReason: reason ?? record.audioReason ?? 'No audio was generated.' }),
|
|
108
|
+
items: record.items,
|
|
109
|
+
remaining: record.remaining,
|
|
110
|
+
context: record.context,
|
|
111
|
+
scriptSource: record.scriptSource,
|
|
112
|
+
cached,
|
|
113
|
+
ms: Date.now() - started,
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
// Hit: the stored briefing is exactly what would be said now.
|
|
117
|
+
if (current?.audioRef) {
|
|
118
|
+
const url = await linkFor(current.audioRef);
|
|
119
|
+
if (url) return result(current, url, true);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Text current but no audio (a failed synthesis last time): reuse the words, retry only the voice.
|
|
123
|
+
const script = current
|
|
124
|
+
? { text: current.text, source: current.scriptSource, segments: current.context.offsets.map((o) => ({ ...o })) }
|
|
125
|
+
: await writeBriefingScript(briefing, deps.scriptLlm, { now, timeZone, name: deps.name });
|
|
126
|
+
|
|
127
|
+
let audioRef: string | undefined;
|
|
128
|
+
let audioMime: string | undefined;
|
|
129
|
+
let audioReason: string | undefined;
|
|
130
|
+
let usage: Record<string, unknown> | undefined;
|
|
131
|
+
try {
|
|
132
|
+
const spoken = await deps.synthesize({ text: script.text });
|
|
133
|
+
audioRef = await deps.audio.put({
|
|
134
|
+
noteId: `briefing-${briefing.context.localDate}-${hash}`,
|
|
135
|
+
audio: spoken.audio,
|
|
136
|
+
mimeType: spoken.mimeType,
|
|
137
|
+
});
|
|
138
|
+
audioMime = spoken.mimeType;
|
|
139
|
+
usage = { provider: spoken.provider, model: spoken.model, characters: spoken.usage.characters, costUsd: spoken.usage.costUsd };
|
|
140
|
+
} catch (error) {
|
|
141
|
+
audioReason = `Speech is unavailable right now: ${reasonOf(error)}`;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const saved = await store.save({
|
|
145
|
+
externalId,
|
|
146
|
+
localDate: briefing.context.localDate,
|
|
147
|
+
contentHash: hash,
|
|
148
|
+
text: script.text,
|
|
149
|
+
scriptSource: script.source,
|
|
150
|
+
items: briefing.items,
|
|
151
|
+
remaining: briefing.remaining,
|
|
152
|
+
context: { ...briefing.context, offsets: offsetsOf(script.segments) },
|
|
153
|
+
...(audioRef ? { audioRef, audioMime } : {}),
|
|
154
|
+
...(audioReason ? { audioReason } : {}),
|
|
155
|
+
...(usage ? { usage } : {}),
|
|
156
|
+
createdAt: new Date(now).toISOString(),
|
|
157
|
+
});
|
|
158
|
+
return result(saved, await linkFor(audioRef), Boolean(current), audioReason);
|
|
159
|
+
}
|
|
@@ -2,3 +2,12 @@ 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';
|
|
8
|
+
export { generateBriefing } from './generate';
|
|
9
|
+
export type { BriefingAudio, BriefingDeps, BriefingRequest, BriefingResult, BriefingSynthesize } from './generate';
|
|
10
|
+
export { briefingResponse, briefingAudioResponse } from './respond';
|
|
11
|
+
export { createEntityBriefingStore, briefingExternalId, BRIEFING_SOURCE } from './store';
|
|
12
|
+
export type { BriefingContextRecord, BriefingRecord, BriefingStore } from './store';
|
|
13
|
+
export { briefingContentHash, hashString, SCRIPT_VERSION } from './cache-key';
|
|
@@ -0,0 +1,87 @@
|
|
|
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
|
+
import { SpeechService } from '@startsimpli/llm/speech';
|
|
8
|
+
|
|
9
|
+
import { voiceAnalyzerDefaults, type CorpusLlmOptions } from '../llm';
|
|
10
|
+
import type { BriefingSynthesize } from './generate';
|
|
11
|
+
import type { BriefingScriptLlm } from './script';
|
|
12
|
+
|
|
13
|
+
export function createBriefingScriptLlm(options: CorpusLlmOptions = {}): BriefingScriptLlm {
|
|
14
|
+
const defaults = voiceAnalyzerDefaults(options.env, options);
|
|
15
|
+
const service =
|
|
16
|
+
options.service ??
|
|
17
|
+
new LLMService<unknown>({
|
|
18
|
+
preferredProvider: defaults.preferredProvider,
|
|
19
|
+
defaultModel: defaults.model,
|
|
20
|
+
// A little warmth: this is wording, not extraction. The validator holds the facts.
|
|
21
|
+
defaultTemperature: options.temperature ?? 0.5,
|
|
22
|
+
defaultMaxTokens: options.maxTokens ?? 900,
|
|
23
|
+
});
|
|
24
|
+
return {
|
|
25
|
+
async write({ system, prompt, timeoutMs }) {
|
|
26
|
+
if (!service.isAvailable()) throw new Error('No LLM provider is reachable for the briefing script.');
|
|
27
|
+
const response = await service.chat(prompt, system, { timeout: timeoutMs ?? options.timeoutMs });
|
|
28
|
+
return response.content;
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// -- speech: voice, model and format are CONFIGURATION, not code ---------------
|
|
34
|
+
|
|
35
|
+
export interface BriefingVoice {
|
|
36
|
+
provider: string;
|
|
37
|
+
voiceId?: string;
|
|
38
|
+
model?: string;
|
|
39
|
+
outputFormat?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Tried in order; the first available provider that succeeds wins. The default
|
|
44
|
+
* is ElevenLabs with the neutral `ai_assistant` voice on flash_v2_5 (measured:
|
|
45
|
+
* 770 chars -> 45 s of audio in 1.5 s for $0.031; v3 took 14 s), OpenAI TTS
|
|
46
|
+
* behind it. Override per deployment with BRIEFING_TTS_PROVIDER, _VOICE_ID,
|
|
47
|
+
* _MODEL and _FORMAT (these name the FIRST entry), or pass `voices`.
|
|
48
|
+
*/
|
|
49
|
+
export function briefingVoices(env: Record<string, string | undefined> = typeof process !== 'undefined' ? process.env : {}): BriefingVoice[] {
|
|
50
|
+
const first: BriefingVoice = {
|
|
51
|
+
provider: env.BRIEFING_TTS_PROVIDER || 'elevenlabs',
|
|
52
|
+
voiceId: env.BRIEFING_TTS_VOICE_ID || (env.BRIEFING_TTS_PROVIDER && env.BRIEFING_TTS_PROVIDER !== 'elevenlabs' ? undefined : 'xB7U4iivDiPcO06WZ47T'),
|
|
53
|
+
model: env.BRIEFING_TTS_MODEL || (env.BRIEFING_TTS_PROVIDER && env.BRIEFING_TTS_PROVIDER !== 'elevenlabs' ? undefined : 'eleven_flash_v2_5'),
|
|
54
|
+
outputFormat: env.BRIEFING_TTS_FORMAT || (env.BRIEFING_TTS_PROVIDER && env.BRIEFING_TTS_PROVIDER !== 'elevenlabs' ? undefined : 'mp3_44100_128'),
|
|
55
|
+
};
|
|
56
|
+
const fallback: BriefingVoice = { provider: 'openai', voiceId: 'alloy', model: 'gpt-4o-mini-tts', outputFormat: 'mp3' };
|
|
57
|
+
return first.provider === 'openai' ? [first, { provider: 'elevenlabs', voiceId: 'xB7U4iivDiPcO06WZ47T', model: 'eleven_flash_v2_5', outputFormat: 'mp3_44100_128' }] : [first, fallback];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function createBriefingSynthesizer(options: {
|
|
61
|
+
voices?: BriefingVoice[];
|
|
62
|
+
/** Build the single-provider service for one entry; default pins `SpeechService` to it. */
|
|
63
|
+
serviceFor?: (provider: string) => Pick<SpeechService, 'synthesize' | 'isAvailable'>;
|
|
64
|
+
env?: Record<string, string | undefined>;
|
|
65
|
+
} = {}): BriefingSynthesize {
|
|
66
|
+
const voices = options.voices ?? briefingVoices(options.env);
|
|
67
|
+
const serviceFor = options.serviceFor ?? ((provider: string) => new SpeechService({ preferredProvider: provider, fallback: false, maxRetries: 1 }));
|
|
68
|
+
return async ({ text }) => {
|
|
69
|
+
let last: unknown = new Error('No text-to-speech provider is configured.');
|
|
70
|
+
for (const voice of voices) {
|
|
71
|
+
const service = serviceFor(voice.provider);
|
|
72
|
+
if (!service.isAvailable()) continue;
|
|
73
|
+
try {
|
|
74
|
+
const out = await service.synthesize({
|
|
75
|
+
text,
|
|
76
|
+
...(voice.voiceId ? { voiceId: voice.voiceId } : {}),
|
|
77
|
+
...(voice.model ? { model: voice.model } : {}),
|
|
78
|
+
...(voice.outputFormat ? { outputFormat: voice.outputFormat } : {}),
|
|
79
|
+
});
|
|
80
|
+
return { audio: out.audio, mimeType: out.mimeType, model: out.model, provider: out.provider, usage: out.usage };
|
|
81
|
+
} catch (error) {
|
|
82
|
+
last = error;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
throw last;
|
|
86
|
+
};
|
|
87
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fetch-`Response` wrappers for the tenant frontend's route files: POST
|
|
3
|
+
* /corpus/briefing and GET /corpus/briefing/<id>/audio. Each mount is a few lines
|
|
4
|
+
* (resolve scope, build deps, call these).
|
|
5
|
+
*/
|
|
6
|
+
import type { CorpusHttp } from '../client';
|
|
7
|
+
import type { TenantEntity } from '../entities';
|
|
8
|
+
import { voiceErrorResponse } from '../voice-manage';
|
|
9
|
+
import { generateBriefing, type BriefingDeps } from './generate';
|
|
10
|
+
|
|
11
|
+
export async function briefingResponse(request: Request, deps: BriefingDeps): Promise<Response> {
|
|
12
|
+
let body: { force?: unknown; timeZone?: unknown } = {};
|
|
13
|
+
try {
|
|
14
|
+
const raw = await request.text();
|
|
15
|
+
if (raw.trim()) body = JSON.parse(raw);
|
|
16
|
+
} catch {
|
|
17
|
+
return Response.json({ detail: 'Send JSON, or nothing.' }, { status: 400 });
|
|
18
|
+
}
|
|
19
|
+
const force = body.force === true || new URL(request.url).searchParams.get('force') === '1';
|
|
20
|
+
const timeZone = typeof body.timeZone === 'string' && body.timeZone ? body.timeZone : undefined;
|
|
21
|
+
if (timeZone) {
|
|
22
|
+
try { new Intl.DateTimeFormat('en-US', { timeZone }); } catch {
|
|
23
|
+
return Response.json({ detail: 'That time zone is not recognised.' }, { status: 400 });
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
return Response.json(await generateBriefing(deps, { force, timeZone }));
|
|
28
|
+
} catch (error) {
|
|
29
|
+
return voiceErrorResponse(error);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The audio, to the briefing's owner only: the row is read as the caller, so another member's id is a 404. */
|
|
34
|
+
export async function briefingAudioResponse(
|
|
35
|
+
id: string,
|
|
36
|
+
deps: {
|
|
37
|
+
http: Pick<CorpusHttp, 'get'>;
|
|
38
|
+
audio: { get(audioRef: string): Promise<{ audio: Uint8Array; mimeType: string }> };
|
|
39
|
+
},
|
|
40
|
+
): Promise<Response> {
|
|
41
|
+
let entity: TenantEntity;
|
|
42
|
+
try {
|
|
43
|
+
entity = await deps.http.get<TenantEntity>(`api/v1/entities/${encodeURIComponent(id)}`);
|
|
44
|
+
} catch (error) {
|
|
45
|
+
const status = (error as { status?: number }).status;
|
|
46
|
+
if (status === 404 || status === 403) return Response.json({ detail: 'Not found.' }, { status: 404 });
|
|
47
|
+
return voiceErrorResponse(error);
|
|
48
|
+
}
|
|
49
|
+
const data = (entity?.data ?? {}) as Record<string, unknown>;
|
|
50
|
+
const ref = data.audio_ref ?? data.audioRef;
|
|
51
|
+
if (data.source !== 'briefing' || typeof ref !== 'string' || !ref) {
|
|
52
|
+
return Response.json({ detail: 'Not found.' }, { status: 404 });
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
const { audio, mimeType } = await deps.audio.get(ref);
|
|
56
|
+
return new Response(audio as BodyInit, {
|
|
57
|
+
headers: { 'content-type': mimeType, 'cache-control': 'private, max-age=300', 'content-length': String(audio.byteLength) },
|
|
58
|
+
});
|
|
59
|
+
} catch (error) {
|
|
60
|
+
return voiceErrorResponse(error);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a day's briefing is kept: ONE tenant row per (owner, local date).
|
|
3
|
+
*
|
|
4
|
+
* A `source_document` with source `briefing` and NO `body`/`summary`: the to-do
|
|
5
|
+
* extractor reads those two fields, so a briefing gives it nothing to
|
|
6
|
+
* re-extract (a briefing is a view of the to-dos, never a source of them). The
|
|
7
|
+
* script lives in `briefing_text`. Owner scope is checked HERE as well as by the
|
|
8
|
+
* tenant: the lookup key carries the owner and a row whose `owner_sub` is not
|
|
9
|
+
* the caller's is treated as absent, because this type may be readable org-wide.
|
|
10
|
+
*/
|
|
11
|
+
import type { CorpusHttp } from '../client';
|
|
12
|
+
import type { TenantEntity } from '../entities';
|
|
13
|
+
import type { BriefingContext, BriefingEntry } from './types';
|
|
14
|
+
import type { ScriptSegment } from './script';
|
|
15
|
+
|
|
16
|
+
export const BRIEFING_SOURCE = 'briefing';
|
|
17
|
+
|
|
18
|
+
export interface BriefingContextRecord extends BriefingContext {
|
|
19
|
+
/** Where each spoken item sits in the text: what "this one" is resolved against. */
|
|
20
|
+
offsets: Array<{ id: string; start: number; end: number }>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface BriefingRecord {
|
|
24
|
+
/** Tenant row id. */
|
|
25
|
+
id: string;
|
|
26
|
+
externalId: string;
|
|
27
|
+
localDate: string;
|
|
28
|
+
contentHash: string;
|
|
29
|
+
text: string;
|
|
30
|
+
scriptSource: 'llm' | 'template';
|
|
31
|
+
items: BriefingEntry[];
|
|
32
|
+
remaining: number;
|
|
33
|
+
context: BriefingContextRecord;
|
|
34
|
+
audioRef?: string;
|
|
35
|
+
audioMime?: string;
|
|
36
|
+
audioReason?: string;
|
|
37
|
+
usage?: Record<string, unknown>;
|
|
38
|
+
createdAt: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export type BriefingDraft = Omit<BriefingRecord, 'id'>;
|
|
42
|
+
|
|
43
|
+
export interface BriefingStore {
|
|
44
|
+
find(externalId: string): Promise<BriefingRecord | null>;
|
|
45
|
+
/** Shallow-merging upsert; returns the row with its id. */
|
|
46
|
+
save(draft: BriefingDraft): Promise<BriefingRecord>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
type StoreHttp = Pick<CorpusHttp, 'get'> & { post<T>(path: string, body?: unknown): Promise<T> };
|
|
50
|
+
|
|
51
|
+
export const briefingExternalId = (ownerSub: string, localDate: string) => `briefing:${localDate}:${ownerSub}`;
|
|
52
|
+
|
|
53
|
+
export function offsetsOf(segments: ScriptSegment[]): BriefingContextRecord['offsets'] {
|
|
54
|
+
return segments.filter((s): s is ScriptSegment & { id: string } => s.id !== null)
|
|
55
|
+
.map((s) => ({ id: s.id, start: s.start, end: s.end }));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function pick(data: Record<string, unknown>, snake: string, camel: string): unknown {
|
|
59
|
+
return data[snake] ?? data[camel];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function toRecord(entity: TenantEntity): BriefingRecord {
|
|
63
|
+
const data = (entity.data ?? {}) as Record<string, unknown>;
|
|
64
|
+
const obj = (value: unknown) => (value && typeof value === 'object' ? (value as Record<string, any>) : {});
|
|
65
|
+
const ctx = obj(pick(data, 'briefing_context', 'briefingContext'));
|
|
66
|
+
const text = (value: unknown) => (typeof value === 'string' ? value : '');
|
|
67
|
+
return {
|
|
68
|
+
id: String(entity.id),
|
|
69
|
+
externalId: text(entity.external_id ?? entity.externalId),
|
|
70
|
+
localDate: text(pick(data, 'briefing_date', 'briefingDate')),
|
|
71
|
+
contentHash: text(pick(data, 'briefing_hash', 'briefingHash')),
|
|
72
|
+
text: text(pick(data, 'briefing_text', 'briefingText')),
|
|
73
|
+
scriptSource: pick(data, 'briefing_source', 'briefingSource') === 'llm' ? 'llm' : 'template',
|
|
74
|
+
items: (pick(data, 'briefing_items', 'briefingItems') as BriefingEntry[] | undefined) ?? [],
|
|
75
|
+
remaining: Number(pick(data, 'briefing_remaining', 'briefingRemaining') ?? 0),
|
|
76
|
+
context: {
|
|
77
|
+
itemIds: ctx.itemIds ?? ctx.item_ids ?? [],
|
|
78
|
+
localDate: ctx.localDate ?? ctx.local_date ?? '',
|
|
79
|
+
timeZone: ctx.timeZone ?? ctx.time_zone ?? 'UTC',
|
|
80
|
+
offsets: ctx.offsets ?? [],
|
|
81
|
+
},
|
|
82
|
+
...(pick(data, 'audio_ref', 'audioRef') ? { audioRef: text(pick(data, 'audio_ref', 'audioRef')) } : {}),
|
|
83
|
+
...(pick(data, 'audio_mime', 'audioMime') ? { audioMime: text(pick(data, 'audio_mime', 'audioMime')) } : {}),
|
|
84
|
+
...(pick(data, 'audio_reason', 'audioReason') ? { audioReason: text(pick(data, 'audio_reason', 'audioReason')) } : {}),
|
|
85
|
+
...(pick(data, 'briefing_usage', 'briefingUsage') ? { usage: obj(pick(data, 'briefing_usage', 'briefingUsage')) } : {}),
|
|
86
|
+
createdAt: text(pick(data, 'occurred_at', 'occurredAt')),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function createEntityBriefingStore(http: StoreHttp, ownerSub: string): BriefingStore {
|
|
91
|
+
const mine = (entity: TenantEntity) => {
|
|
92
|
+
const sub = (entity as { owner_sub?: string; ownerSub?: string }).owner_sub
|
|
93
|
+
?? (entity as { ownerSub?: string }).ownerSub
|
|
94
|
+
?? ((entity.data ?? {}) as Record<string, unknown>).owner_sub;
|
|
95
|
+
return sub === ownerSub;
|
|
96
|
+
};
|
|
97
|
+
return {
|
|
98
|
+
async find(externalId) {
|
|
99
|
+
if (!externalId.endsWith(`:${ownerSub}`)) return null;
|
|
100
|
+
const page = await http.get<{ results?: TenantEntity[] }>('api/v1/entities', {
|
|
101
|
+
params: { type: 'source_document', external_id__in: externalId, page_size: 5 },
|
|
102
|
+
});
|
|
103
|
+
const hit = (page.results ?? []).find((r) => (r.external_id ?? r.externalId) === externalId && mine(r));
|
|
104
|
+
return hit ? toRecord(hit) : null;
|
|
105
|
+
},
|
|
106
|
+
async save(draft) {
|
|
107
|
+
const row = await http.post<TenantEntity>('api/v1/entities/upsert', {
|
|
108
|
+
entity_type: 'source_document',
|
|
109
|
+
external_id: draft.externalId,
|
|
110
|
+
name: `Briefing ${draft.localDate}`,
|
|
111
|
+
data: {
|
|
112
|
+
title: `Briefing ${draft.localDate}`,
|
|
113
|
+
source: BRIEFING_SOURCE,
|
|
114
|
+
source_label: 'Briefing',
|
|
115
|
+
source_ref: draft.externalId,
|
|
116
|
+
occurred_at: draft.createdAt,
|
|
117
|
+
owner_sub: ownerSub,
|
|
118
|
+
briefing_date: draft.localDate,
|
|
119
|
+
briefing_hash: draft.contentHash,
|
|
120
|
+
briefing_text: draft.text,
|
|
121
|
+
briefing_source: draft.scriptSource,
|
|
122
|
+
briefing_items: draft.items,
|
|
123
|
+
briefing_remaining: draft.remaining,
|
|
124
|
+
briefing_context: draft.context,
|
|
125
|
+
audio_ref: draft.audioRef ?? '',
|
|
126
|
+
audio_mime: draft.audioMime ?? '',
|
|
127
|
+
audio_reason: draft.audioReason ?? '',
|
|
128
|
+
...(draft.usage ? { briefing_usage: draft.usage } : {}),
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
return { ...draft, id: String(row.id) };
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
}
|