@startsimpli/integrations 0.2.119 → 0.2.121
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-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 +6 -0
- package/src/corpus/briefing/llm.ts +58 -0
- package/src/corpus/briefing/respond.ts +62 -0
- package/src/corpus/briefing/store.ts +134 -0
- package/src/corpus/llm.ts +2 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@startsimpli/integrations",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.121",
|
|
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/ui": "^0.4.171",
|
|
54
53
|
"@startsimpli/auth": "^0.4.50",
|
|
54
|
+
"@startsimpli/ui": "^0.4.171",
|
|
55
55
|
"@startsimpli/utils": "^0.4.17"
|
|
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,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
|
+
}
|
|
@@ -5,3 +5,9 @@ export type {
|
|
|
5
5
|
export { writeBriefingScript, templateScript, scriptPrompt, scriptSystemPrompt } from './script';
|
|
6
6
|
export type { BriefingScript, BriefingScriptLlm, BriefingScriptOptions, ScriptSegment } from './script';
|
|
7
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';
|
|
@@ -4,8 +4,10 @@
|
|
|
4
4
|
* the reason `corpus/llm.ts` gives (no provider client in a browser bundle).
|
|
5
5
|
*/
|
|
6
6
|
import { LLMService } from '@startsimpli/llm';
|
|
7
|
+
import { SpeechService } from '@startsimpli/llm/speech';
|
|
7
8
|
|
|
8
9
|
import { voiceAnalyzerDefaults, type CorpusLlmOptions } from '../llm';
|
|
10
|
+
import type { BriefingSynthesize } from './generate';
|
|
9
11
|
import type { BriefingScriptLlm } from './script';
|
|
10
12
|
|
|
11
13
|
export function createBriefingScriptLlm(options: CorpusLlmOptions = {}): BriefingScriptLlm {
|
|
@@ -27,3 +29,59 @@ export function createBriefingScriptLlm(options: CorpusLlmOptions = {}): Briefin
|
|
|
27
29
|
},
|
|
28
30
|
};
|
|
29
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,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
|
+
}
|
package/src/corpus/llm.ts
CHANGED
|
@@ -649,4 +649,5 @@ export function createVoiceTranscriber(
|
|
|
649
649
|
};
|
|
650
650
|
}
|
|
651
651
|
|
|
652
|
-
export { createBriefingScriptLlm } from './briefing/llm';
|
|
652
|
+
export { briefingVoices, createBriefingScriptLlm, createBriefingSynthesizer } from './briefing/llm';
|
|
653
|
+
export type { BriefingVoice } from './briefing/llm';
|