@startsimpli/integrations 0.2.124 → 0.2.126
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 +3 -3
- package/src/__tests__/briefing-actions.test.ts +316 -0
- package/src/__tests__/briefing-compose.test.ts +6 -0
- package/src/__tests__/briefing-intent-table.ts +121 -0
- package/src/__tests__/briefing-intent.test.ts +281 -0
- package/src/corpus/briefing/actions/confirm.ts +65 -0
- package/src/corpus/briefing/actions/execute.ts +153 -0
- package/src/corpus/briefing/actions/index.ts +9 -0
- package/src/corpus/briefing/actions/log.ts +63 -0
- package/src/corpus/briefing/actions/seam.ts +50 -0
- package/src/corpus/briefing/actions/types.ts +90 -0
- package/src/corpus/briefing/compose.ts +3 -0
- package/src/corpus/briefing/index.ts +2 -0
- package/src/corpus/briefing/intent/dates.ts +195 -0
- package/src/corpus/briefing/intent/describe.ts +26 -0
- package/src/corpus/briefing/intent/grammar.ts +175 -0
- package/src/corpus/briefing/intent/ground.ts +95 -0
- package/src/corpus/briefing/intent/index.ts +11 -0
- package/src/corpus/briefing/intent/match.ts +56 -0
- package/src/corpus/briefing/intent/model.ts +135 -0
- package/src/corpus/briefing/intent/position.ts +49 -0
- package/src/corpus/briefing/intent/resolve.ts +49 -0
- package/src/corpus/briefing/intent/target.ts +72 -0
- package/src/corpus/briefing/intent/types.ts +61 -0
- package/src/corpus/client.ts +1 -0
- package/src/corpus/types.ts +4 -1
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
parseWithGrammar, resolveVoiceIntent, parseWhen, readingAt,
|
|
5
|
+
type BriefingScriptLlm, type VoiceAction,
|
|
6
|
+
} from '../corpus/briefing';
|
|
7
|
+
import { BRIEFED, NOW, OTHER_OPEN, TABLE, TZ, baseContext, type Row } from './briefing-intent-table';
|
|
8
|
+
|
|
9
|
+
const ctxOf = (row: Row) => baseContext({
|
|
10
|
+
utterance: row.say,
|
|
11
|
+
readingId: row.reading === undefined ? null : row.reading,
|
|
12
|
+
hasUndo: row.hasUndo ?? true,
|
|
13
|
+
...(row.open ? { open: row.open } : {}),
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
/** Compare actions the way the table states them: clarify matches on type alone. */
|
|
17
|
+
const shape = (actions: VoiceAction[]) => actions.map((a) => (a.type === 'clarify' ? { type: 'clarify' } : a));
|
|
18
|
+
const wanted = (row: Row) => shape(row.expect);
|
|
19
|
+
/** The parser adds a spoken `label` for the confirmation; the table does not state it. */
|
|
20
|
+
const stripLabel = (actions: VoiceAction[]) => actions.map((a) => {
|
|
21
|
+
if (a.type !== 'defer' && a.type !== 'pull_today') return a;
|
|
22
|
+
const { label: _label, ...rest } = a as VoiceAction & { label?: string };
|
|
23
|
+
return rest as VoiceAction;
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
function toWire(a: VoiceAction): Record<string, unknown> {
|
|
27
|
+
switch (a.type) {
|
|
28
|
+
case 'defer': return { type: 'defer', item_id: a.itemId, to: a.to };
|
|
29
|
+
case 'pull_today': return { type: 'pull_today', item_id: a.itemId };
|
|
30
|
+
case 'done': case 'drop': return { type: a.type, item_id: a.itemId };
|
|
31
|
+
case 'set_priority': return { type: 'set_priority', item_id: a.itemId, priority: a.priority };
|
|
32
|
+
case 'add_item': return { type: 'add_item', title: a.title, due: a.dueDate };
|
|
33
|
+
case 'clarify': return { type: 'clarify', question: 'Which one?' };
|
|
34
|
+
default: return { type: a.type };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
describe('the utterance table', () => {
|
|
39
|
+
it('has 30+ rows across every category', () => {
|
|
40
|
+
expect(TABLE.length).toBeGreaterThanOrEqual(30);
|
|
41
|
+
const categories = new Set(TABLE.map((r) => r.category));
|
|
42
|
+
for (const c of ['defer', 'reschedule', 'pull_today', 'done', 'drop', 'priority', 'add', 'undo', 'multi', 'ambiguous', 'unknown', 'none'])
|
|
43
|
+
expect(categories.has(c as Row['category'])).toBe(true);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
describe('deterministic grammar (no model at all)', () => {
|
|
47
|
+
const covered = TABLE.filter((r) => !r.llmOnly);
|
|
48
|
+
it('covers at least ten rows without an LLM', () => expect(covered.length).toBeGreaterThanOrEqual(10));
|
|
49
|
+
it.each(covered.map((r) => [`${r.category}: ${r.name}`, r] as const))('%s', (_n, row) => {
|
|
50
|
+
const out = parseWithGrammar(ctxOf(row));
|
|
51
|
+
expect(shape(stripLabel(out.actions))).toEqual(wanted(row));
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
describe('resolveVoiceIntent with a model that answers well', () => {
|
|
56
|
+
it.each(TABLE.filter((r) => r.say.trim()).map((r) => [`${r.category}: ${r.name}`, r] as const))('%s', async (_n, row) => {
|
|
57
|
+
// The fake model "understands" by replaying what the table expects, in the wire shape.
|
|
58
|
+
const llm: BriefingScriptLlm = { write: async () => JSON.stringify({ confidence: 0.95, actions: row.expect.map(toWire) }) };
|
|
59
|
+
const out = await resolveVoiceIntent(ctxOf(row), { llm });
|
|
60
|
+
expect(out.source).toBe('llm');
|
|
61
|
+
expect(shape(stripLabel(out.actions))).toEqual(wanted(row));
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
describe('specific spoken answers', () => {
|
|
67
|
+
it('asks which one, naming up to three briefed items', () => {
|
|
68
|
+
const out = parseWithGrammar(baseContext({ utterance: 'move that one', readingId: null }));
|
|
69
|
+
expect(out.actions[0].type).toBe('clarify');
|
|
70
|
+
const q = (out.actions[0] as { question: string }).question;
|
|
71
|
+
expect(q).toMatch(/^Which one: /);
|
|
72
|
+
expect(q).toContain('marketing wireframes');
|
|
73
|
+
expect(q).toContain('V2');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('never invents an item: an unknown subject asks, and offers to add it', () => {
|
|
77
|
+
const out = parseWithGrammar(baseContext({ utterance: 'pull up the tax thing' }));
|
|
78
|
+
expect(out.actions).toEqual([{ type: 'clarify', question: 'I could not find a tax item. Say add it to create one.' }]);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('asks for the date when it is missing, and for the item when "later" has no reading item', () => {
|
|
82
|
+
const noDate = parseWithGrammar(baseContext({ utterance: 'move this one', readingId: 'pr' }));
|
|
83
|
+
expect((noDate.actions[0] as { question: string }).question).toMatch(/when/i);
|
|
84
|
+
const noItem = parseWithGrammar(baseContext({ utterance: 'later', readingId: null }));
|
|
85
|
+
expect(noItem.actions[0].type).toBe('clarify');
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('with nothing to undo, says so instead of undoing', () => {
|
|
89
|
+
const out = parseWithGrammar(baseContext({ utterance: 'undo', hasUndo: false }));
|
|
90
|
+
expect((out.actions[0] as { question: string }).question).toMatch(/nothing to undo/i);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('asks to repeat anything it does not understand', () => {
|
|
94
|
+
const out = parseWithGrammar(baseContext({ utterance: 'what a lovely morning' }));
|
|
95
|
+
expect((out.actions[0] as { question: string }).question).toMatch(/say that again/i);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it('"the next one" is the item after the one being read; "the third one" is by position', () => {
|
|
99
|
+
expect(parseWithGrammar(baseContext({ utterance: 'done with the next one', readingId: 'wire' })).actions)
|
|
100
|
+
.toEqual([{ type: 'done', itemId: 'v2' }]);
|
|
101
|
+
expect(parseWithGrammar(baseContext({ utterance: 'drop the third one' })).actions)
|
|
102
|
+
.toEqual([{ type: 'drop', itemId: 'paper' }]);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('keeps the spoken date phrase for the confirmation', () => {
|
|
106
|
+
const out = parseWithGrammar(baseContext({ utterance: 'next week', readingId: 'v2' }));
|
|
107
|
+
expect(out.actions[0]).toMatchObject({ type: 'defer', itemId: 'v2', to: '2026-11-09', label: 'next week' });
|
|
108
|
+
});
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
describe('the model path is checked, never trusted', () => {
|
|
112
|
+
const ctx = baseContext({ utterance: 'move this one to later', readingId: 'paper' });
|
|
113
|
+
const answer = (body: unknown): BriefingScriptLlm => ({ write: async () => (typeof body === 'string' ? body : JSON.stringify(body)) });
|
|
114
|
+
|
|
115
|
+
it('test_item_ids_must_exist_in_open_items_hallucinated_id_rejected', async () => {
|
|
116
|
+
const llm = answer({ confidence: 0.99, actions: [{ type: 'defer', item_id: 'ghost', to: 'later' }] });
|
|
117
|
+
const out = await resolveVoiceIntent(ctx, { llm });
|
|
118
|
+
expect(out.source).toBe('grammar');
|
|
119
|
+
expect(out.actions).toEqual([{ type: 'defer', itemId: 'paper', to: 'later', label: 'later' }]);
|
|
120
|
+
expect(out.notes.join(' ')).toContain('unknown item');
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it('test_llm_failure_uses_deterministic_grammar_covering_done_later_tomorrow_today_undo_drop_and_otherwise_asks_to_repeat', async () => {
|
|
124
|
+
const down: BriefingScriptLlm = { write: vi.fn(async () => { throw new Error('boom'); }) };
|
|
125
|
+
const run = (say: string, reading: string | null = 'pr') => resolveVoiceIntent(baseContext({ utterance: say, readingId: reading }), { llm: down });
|
|
126
|
+
expect((await run('done')).actions[0]).toMatchObject({ type: 'done', itemId: 'pr' });
|
|
127
|
+
expect((await run('later')).actions[0]).toMatchObject({ type: 'defer', to: 'later' });
|
|
128
|
+
expect((await run('tomorrow')).actions[0]).toMatchObject({ type: 'defer', to: '2026-11-05' });
|
|
129
|
+
expect((await run('do this today')).actions[0]).toMatchObject({ type: 'pull_today', itemId: 'pr' });
|
|
130
|
+
expect((await run('undo')).actions[0]).toEqual({ type: 'undo' });
|
|
131
|
+
expect((await run('drop it')).actions[0]).toMatchObject({ type: 'drop', itemId: 'pr' });
|
|
132
|
+
const odd = await run('hmm the purple elephant sings');
|
|
133
|
+
expect(odd.actions[0]).toMatchObject({ type: 'clarify' });
|
|
134
|
+
expect(odd.source).toBe('grammar');
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it('test_confidence_below_threshold_asks_clarification_instead_of_acting', async () => {
|
|
138
|
+
const llm = answer({ confidence: 0.3, actions: [{ type: 'done', item_id: 'paper' }] });
|
|
139
|
+
const out = await resolveVoiceIntent(ctx, { llm });
|
|
140
|
+
expect(out.actions).toHaveLength(1);
|
|
141
|
+
expect(out.actions[0].type).toBe('clarify');
|
|
142
|
+
expect((out.actions[0] as { question: string }).question).toMatch(/not sure|say that again/i);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it('rejects garbage, bad priorities and bad dates, then falls back', async () => {
|
|
146
|
+
for (const body of ['not json', { confidence: 1, actions: [{ type: 'set_priority', item_id: 'paper', priority: 9 }] },
|
|
147
|
+
{ confidence: 1, actions: [{ type: 'defer', item_id: 'paper', to: '2026-13-45' }] }, { confidence: 1, actions: [{ type: 'explode' }] }]) {
|
|
148
|
+
const out = await resolveVoiceIntent(ctx, { llm: answer(body) });
|
|
149
|
+
expect(out.source).toBe('grammar');
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it('gives the model the spoken list, the item being read and today in the listener zone', async () => {
|
|
154
|
+
const write = vi.fn(async (_: { system: string; prompt: string }) => JSON.stringify({ confidence: 1, actions: [{ type: 'done', item_id: 'paper' }] }));
|
|
155
|
+
await resolveVoiceIntent(ctx, { llm: { write } });
|
|
156
|
+
const { prompt } = write.mock.calls[0][0];
|
|
157
|
+
expect(prompt).toContain('Wednesday 2026-11-04');
|
|
158
|
+
expect(prompt).toContain('[id:paper]');
|
|
159
|
+
expect(prompt).toMatch(/being read.*paper/is);
|
|
160
|
+
expect(prompt).toContain('[id:john]');
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it('a model "defer to today" becomes pull_today, and a date phrase from the model is understood', async () => {
|
|
164
|
+
const a = await resolveVoiceIntent(ctx, { llm: answer({ confidence: 1, actions: [{ type: 'defer', item_id: 'paper', to: '2026-11-04' }] }) });
|
|
165
|
+
expect(a.actions[0]).toMatchObject({ type: 'pull_today', itemId: 'paper' });
|
|
166
|
+
const b = await resolveVoiceIntent(baseContext({ utterance: 'push this to next friday', readingId: 'paper' }),
|
|
167
|
+
{ llm: answer({ confidence: 1, actions: [{ type: 'defer', item_id: 'paper', to: 'next friday' }] }) });
|
|
168
|
+
expect(b.actions[0]).toMatchObject({ type: 'defer', to: '2026-11-13' });
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
describe('a model guess is not an answer (grounding)', () => {
|
|
174
|
+
const answer = (actions: unknown[]): BriefingScriptLlm => ({ write: async () => JSON.stringify({ confidence: 0.95, actions }) });
|
|
175
|
+
const run = (say: string, reading: string | null, actions: unknown[]) =>
|
|
176
|
+
resolveVoiceIntent(baseContext({ utterance: say, readingId: reading }), { llm: answer(actions) });
|
|
177
|
+
|
|
178
|
+
it('nothing is being read and the words name nothing: the model\'s pick is dropped for a question', async () => {
|
|
179
|
+
const out = await run('mark it done', null, [{ type: 'done', item_id: 'wire' }]);
|
|
180
|
+
expect(out.source).toBe('grammar');
|
|
181
|
+
expect(out.actions[0].type).toBe('clarify');
|
|
182
|
+
expect(out.notes.join(' ')).toContain('ungrounded');
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it('"pull" in "pull it up" is not "pull request"', async () => {
|
|
186
|
+
const out = await run('what about that other thing, pull it up to today', null, [{ type: 'pull_today', item_id: 'pr' }]);
|
|
187
|
+
expect(out.source).toBe('grammar');
|
|
188
|
+
expect(out.actions[0].type).toBe('clarify');
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
it('a model that moves with no date in the reply is asked again', async () => {
|
|
192
|
+
const out = await run('move this one', 'pr', [{ type: 'defer', item_id: 'pr', to: 'later' }]);
|
|
193
|
+
expect(out.actions[0].type).toBe('clarify');
|
|
194
|
+
expect((out.actions[0] as { question: string }).question).toMatch(/when/i);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it('the item being read is not acted on when the words name a different one', async () => {
|
|
198
|
+
const out = await run('the bench one is done', 'pr', [{ type: 'done', item_id: 'pr' }]);
|
|
199
|
+
expect(out.actions).toEqual([{ type: 'done', itemId: 'bench' }]);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
it('two items that fit the words equally are a question, not a coin flip', async () => {
|
|
203
|
+
const out = await run('mark the platform one done', null, [{ type: 'done', item_id: 'pr' }]);
|
|
204
|
+
expect(out.actions[0].type).toBe('clarify');
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
it('a model date that contradicts the words is not trusted: "to today" is not "later"', async () => {
|
|
208
|
+
const out = await run('move the denver trip to today', null, [{ type: 'defer', item_id: 'denver', to: 'later' }]);
|
|
209
|
+
expect(out.actions).toEqual([{ type: 'pull_today', itemId: 'denver', label: 'today' }]);
|
|
210
|
+
expect(out.source).toBe('grammar');
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
it('when the model only asks but the plain rules find one clear match, the match wins', async () => {
|
|
214
|
+
const out = await run('bring up the lease call', null, [{ type: 'clarify', question: 'Which one?' }]);
|
|
215
|
+
expect(out.actions).toEqual([{ type: 'pull_today', itemId: 'john', label: 'today' }]);
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
it('a well-grounded model answer is kept (source llm)', async () => {
|
|
219
|
+
const out = await run('the bench thing is finished', 'pr', [{ type: 'done', item_id: 'bench' }]);
|
|
220
|
+
expect(out.source).toBe('llm');
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
describe('dates are resolved in the listener zone, relative to today', () => {
|
|
225
|
+
it('test_dates_resolved_in_user_tz_relative_to_today_not_utc', () => {
|
|
226
|
+
// 02:00 UTC on the 5th is still the evening of the 4th in New York: "tomorrow" is the 5th there.
|
|
227
|
+
const lateUtc = Date.parse('2026-11-05T02:00:00Z');
|
|
228
|
+
expect(parseWhen('tomorrow', lateUtc, 'America/New_York')?.date).toBe('2026-11-05');
|
|
229
|
+
expect(parseWhen('tomorrow', lateUtc, 'UTC')?.date).toBe('2026-11-06');
|
|
230
|
+
expect(parseWhen('today', lateUtc, 'America/New_York')?.date).toBe('2026-11-04');
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
it.each([
|
|
234
|
+
['tomorrow', '2026-11-05'], ['tonight', '2026-11-04'], ['today', '2026-11-04'], ['later today', '2026-11-04'],
|
|
235
|
+
['the day after tomorrow', '2026-11-06'],
|
|
236
|
+
['friday', '2026-11-06'], ['this friday', '2026-11-06'], ['next friday', '2026-11-13'], ['wednesday', '2026-11-11'],
|
|
237
|
+
['monday', '2026-11-09'], ['next monday', '2026-11-09'], ['next week', '2026-11-09'],
|
|
238
|
+
['this weekend', '2026-11-07'], ['end of the week', '2026-11-06'], ['next month', '2026-12-01'],
|
|
239
|
+
['in two days', '2026-11-06'], ['in a week', '2026-11-11'], ['in 2 weeks', '2026-11-18'],
|
|
240
|
+
['november twelfth', '2026-11-12'], ['the 12th', '2026-11-12'], ['december 3', '2026-12-03'], ['the third', '2026-12-03'],
|
|
241
|
+
['later', 'later'], ['later this week', '2026-11-06'], ['some other time', 'later'], ['sometime', 'later'],
|
|
242
|
+
])('%s -> %s', (phrase, want) => {
|
|
243
|
+
const w = parseWhen(phrase, NOW, TZ);
|
|
244
|
+
expect(w && (w.later ? 'later' : w.date)).toBe(want);
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
it('does not understand things that are not dates', () => {
|
|
248
|
+
expect(parseWhen('the purple elephant', NOW, TZ)).toBeNull();
|
|
249
|
+
});
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
describe('"this one" by playback position', () => {
|
|
253
|
+
const ctx = {
|
|
254
|
+
itemIds: ['a', 'b', 'c'], localDate: '2026-11-04', timeZone: TZ,
|
|
255
|
+
offsets: [{ id: 'a', start: 20, end: 60 }, { id: 'b', start: 61, end: 120 }, { id: 'c', start: 121, end: 170 }],
|
|
256
|
+
};
|
|
257
|
+
it('is the item whose sentence is being spoken', () => {
|
|
258
|
+
expect(readingAt(ctx, { charPosition: 30 })).toBe('a');
|
|
259
|
+
expect(readingAt(ctx, { charPosition: 100 })).toBe('b');
|
|
260
|
+
});
|
|
261
|
+
it('is the last fully spoken item when playback sits between items (documented rule)', () => {
|
|
262
|
+
expect(readingAt(ctx, { charPosition: 60.5 })).toBe('a');
|
|
263
|
+
expect(readingAt(ctx, { charPosition: 125 })).toBe('c');
|
|
264
|
+
expect(readingAt(ctx, { charPosition: 400 })).toBe('c');
|
|
265
|
+
});
|
|
266
|
+
it('is nothing before the first item', () => expect(readingAt(ctx, { charPosition: 3 })).toBeNull());
|
|
267
|
+
it('estimates the position from seconds when the provider gave no word timings', () => {
|
|
268
|
+
expect(readingAt(ctx, { seconds: 2 })).toBe('a'); // 2 s x 15 chars/s = 30
|
|
269
|
+
expect(readingAt(ctx, { seconds: 7 })).toBe('b'); // 105
|
|
270
|
+
});
|
|
271
|
+
it('uses the fraction of the audio when its length is known', () => {
|
|
272
|
+
expect(readingAt(ctx, { seconds: 10, durationSeconds: 20, textLength: 170 })).toBe('b'); // 85
|
|
273
|
+
});
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
describe('fixture sanity', () => {
|
|
277
|
+
it('has the shape the tests assume', () => {
|
|
278
|
+
expect(BRIEFED.map((i) => i.id)).toEqual(['wire', 'v2', 'paper', 'pr', 'bench']);
|
|
279
|
+
expect(OTHER_OPEN.length).toBe(3);
|
|
280
|
+
});
|
|
281
|
+
});
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** What is said back after an action: plain sentences built from the item's title and a spoken date. */
|
|
2
|
+
import { localDate } from '../compose';
|
|
3
|
+
import { spokenWhen } from '../intent/dates';
|
|
4
|
+
import { PRIORITY_NAMES } from '../intent/describe';
|
|
5
|
+
import { speakable } from '../speak';
|
|
6
|
+
import type { BriefingAudio, BriefingSynthesize } from '../generate';
|
|
7
|
+
import type { ItemPatch, UndoEntry } from './types';
|
|
8
|
+
import type { VoiceAction } from '../intent/types';
|
|
9
|
+
|
|
10
|
+
export const shortTitle = (title: string) => speakable(title, 8) || 'that item';
|
|
11
|
+
|
|
12
|
+
export function confirmText(action: VoiceAction, title: string, now: number, timeZone: string): string {
|
|
13
|
+
const today = localDate(now, timeZone);
|
|
14
|
+
const t = shortTitle(title);
|
|
15
|
+
switch (action.type) {
|
|
16
|
+
case 'defer': return `Moved ${t} to ${action.to === 'later' ? 'later' : action.label ?? spokenWhen(action.to, today)}.`;
|
|
17
|
+
case 'pull_today': return `Pulled ${t} into today.`;
|
|
18
|
+
case 'done': return `Marked ${t} done.`;
|
|
19
|
+
case 'drop': return `Dropped ${t}.`;
|
|
20
|
+
case 'set_priority': return `Made ${t} ${PRIORITY_NAMES[action.priority] ?? `priority ${action.priority}`}.`;
|
|
21
|
+
case 'add_item': return `Added ${shortTitle(action.title)}${action.dueDate ? ` for ${spokenWhen(action.dueDate, today)}` : ''}.`;
|
|
22
|
+
default: return '';
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** "Undid it. Order dad's bench is back to Wednesday." */
|
|
27
|
+
export function undoText(entry: UndoEntry, now: number, timeZone: string): string {
|
|
28
|
+
const today = localDate(now, timeZone);
|
|
29
|
+
const t = shortTitle(entry.title);
|
|
30
|
+
if (entry.kind === 'create') return `Undid it. ${t} is removed.`;
|
|
31
|
+
const b: ItemPatch = entry.before;
|
|
32
|
+
const parts: string[] = [];
|
|
33
|
+
if ('dueAt' in b) parts.push(b.dueAt ? `due ${spokenWhen(String(b.dueAt).slice(0, 10), today)}` : 'no date');
|
|
34
|
+
if ('status' in b && b.status) parts.push(b.status === 'open' ? 'open' : String(b.status));
|
|
35
|
+
if ('priority' in b) parts.push(b.priority === null || b.priority === undefined ? 'no priority' : PRIORITY_NAMES[b.priority] ?? `priority ${b.priority}`);
|
|
36
|
+
return `Undid it. ${t} is back to ${parts.join(', ') || 'how it was'}.`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface SpokenConfirmation {
|
|
40
|
+
text: string;
|
|
41
|
+
/** Short-lived link to the spoken version, or null when only text is available. */
|
|
42
|
+
audioUrl: string | null;
|
|
43
|
+
mimeType?: string;
|
|
44
|
+
reason?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Text is always returned; speech is best effort (a synthesis failure never loses the confirmation). */
|
|
48
|
+
export async function speakConfirmation(input: {
|
|
49
|
+
text: string;
|
|
50
|
+
clientActionId: string;
|
|
51
|
+
synthesize?: BriefingSynthesize;
|
|
52
|
+
audio?: Pick<BriefingAudio, 'put' | 'url'>;
|
|
53
|
+
ttlSeconds?: number;
|
|
54
|
+
}): Promise<SpokenConfirmation> {
|
|
55
|
+
if (!input.text.trim()) return { text: input.text, audioUrl: null, reason: 'nothing to say' };
|
|
56
|
+
if (!input.synthesize || !input.audio) return { text: input.text, audioUrl: null, reason: 'speech is not configured' };
|
|
57
|
+
try {
|
|
58
|
+
const out = await input.synthesize({ text: input.text });
|
|
59
|
+
const ref = await input.audio.put({ noteId: `confirm-${input.clientActionId}`, audio: out.audio, mimeType: out.mimeType });
|
|
60
|
+
const audioUrl = await input.audio.url(ref, input.ttlSeconds ?? 300, `confirm-${input.clientActionId}`);
|
|
61
|
+
return { text: input.text, audioUrl, mimeType: out.mimeType };
|
|
62
|
+
} catch (error) {
|
|
63
|
+
return { text: input.text, audioUrl: null, reason: error instanceof Error ? error.message : String(error) };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE EXECUTOR: apply parsed voice actions through the item edit seam, safely.
|
|
3
|
+
*
|
|
4
|
+
* - IDEMPOTENT: every action is keyed `<clientActionId>#<n>`; a retry or a double
|
|
5
|
+
* tap replays what was said, writes nothing, pushes nothing on the undo stack.
|
|
6
|
+
* - REVERSIBLE: each real change records before/after; "undo" restores the last
|
|
7
|
+
* five, newest first, through the same seam (so the reversal also reaches
|
|
8
|
+
* wherever edits go). If the item changed since, undo asks instead of overwriting.
|
|
9
|
+
* - HONEST: a failed write is reported on that action and the rest still run.
|
|
10
|
+
* Only what really changed is on the undo stack.
|
|
11
|
+
*/
|
|
12
|
+
import { localDate } from '../compose';
|
|
13
|
+
import type { VoiceAction } from '../intent/types';
|
|
14
|
+
import { confirmText, shortTitle, undoText } from './confirm';
|
|
15
|
+
import { REMEMBERED_ACTIONS, UNDO_DEPTH } from './log';
|
|
16
|
+
import type {
|
|
17
|
+
ActionLog, ActionLogStore, ActionResult, EditableItem, ExecuteOutcome, ItemEditSeam, ItemPatch, UndoEntry,
|
|
18
|
+
} from './types';
|
|
19
|
+
|
|
20
|
+
export interface ExecuteInput {
|
|
21
|
+
actions: VoiceAction[];
|
|
22
|
+
/** Generated by the client per reply; sending the same one again is a replay. */
|
|
23
|
+
clientActionId: string;
|
|
24
|
+
seam: ItemEditSeam;
|
|
25
|
+
log: ActionLogStore;
|
|
26
|
+
ownerSub: string;
|
|
27
|
+
now?: () => number;
|
|
28
|
+
/** The listener's zone: "today" is theirs. */
|
|
29
|
+
timeZone: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const sameDay = (a: unknown, b: unknown) => (a ? String(a).slice(0, 10) : null) === (b ? String(b).slice(0, 10) : null);
|
|
33
|
+
|
|
34
|
+
/** The fields a patch changes, read off an item, so a reversal can put them back. */
|
|
35
|
+
function snapshot(item: EditableItem, patch: ItemPatch): ItemPatch {
|
|
36
|
+
const before: ItemPatch = {};
|
|
37
|
+
for (const key of Object.keys(patch) as Array<keyof ItemPatch>) {
|
|
38
|
+
if (key === 'dueAt') before.dueAt = item.dueAt ?? null;
|
|
39
|
+
else if (key === 'priority') before.priority = item.priority ?? null;
|
|
40
|
+
else if (key === 'resolvedAt') before.resolvedAt = item.resolvedAt ?? null;
|
|
41
|
+
else if (key === 'statusReason') before.statusReason = item.statusReason ?? '';
|
|
42
|
+
else if (key === 'status') before.status = item.status;
|
|
43
|
+
}
|
|
44
|
+
return before;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Has the item moved on from what we left it as? Only fields people care about are compared. */
|
|
48
|
+
function changedSince(item: EditableItem, after: ItemPatch): boolean {
|
|
49
|
+
if ('dueAt' in after && !sameDay(item.dueAt, after.dueAt)) return true;
|
|
50
|
+
if ('status' in after && item.status !== after.status) return true;
|
|
51
|
+
if ('priority' in after && (item.priority ?? null) !== (after.priority ?? null)) return true;
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function patchFor(action: VoiceAction, today: string, nowIso: string): ItemPatch | null {
|
|
56
|
+
switch (action.type) {
|
|
57
|
+
case 'defer': return { dueAt: action.to === 'later' ? null : action.to };
|
|
58
|
+
case 'pull_today': return { dueAt: today };
|
|
59
|
+
case 'done': return { status: 'done', resolvedAt: nowIso, statusReason: 'Done by voice reply' };
|
|
60
|
+
case 'drop': return { status: 'dropped', statusReason: 'Dropped by voice reply' };
|
|
61
|
+
case 'set_priority': return { priority: action.priority };
|
|
62
|
+
default: return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function pushUndo(log: ActionLog, entry: UndoEntry) {
|
|
67
|
+
log.stack.push(entry);
|
|
68
|
+
while (log.stack.length > UNDO_DEPTH) log.stack.shift();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function remember(log: ActionLog, key: string, result: ActionResult) {
|
|
72
|
+
log.applied[key] = result;
|
|
73
|
+
log.order.push(key);
|
|
74
|
+
while (log.order.length > REMEMBERED_ACTIONS) delete log.applied[log.order.shift() as string];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function undoOne(log: ActionLog, input: ExecuteInput, now: number): Promise<ActionResult> {
|
|
78
|
+
const entry = log.stack[log.stack.length - 1];
|
|
79
|
+
if (!entry) return { status: 'asked', spoken: 'There is nothing to undo.' };
|
|
80
|
+
log.stack.pop(); // popped either way: an entry that cannot be restored must not block the ones under it
|
|
81
|
+
try {
|
|
82
|
+
const item = await input.seam.load(entry.itemId);
|
|
83
|
+
if (!item) return { status: 'asked', spoken: `${shortTitle(entry.title)} is gone, so I could not undo that.`, itemId: entry.itemId };
|
|
84
|
+
if (entry.kind === 'create') {
|
|
85
|
+
if (item.status !== 'open') return { status: 'asked', spoken: `${shortTitle(entry.title)} changed since, so I left it.`, itemId: entry.itemId };
|
|
86
|
+
await input.seam.update(item, { status: 'dropped', statusReason: 'Undone by voice reply' });
|
|
87
|
+
} else {
|
|
88
|
+
if (changedSince(item, entry.after)) {
|
|
89
|
+
return { status: 'asked', spoken: `${shortTitle(entry.title)} changed since, so I did not undo that. Tell me what you want instead.`, itemId: entry.itemId };
|
|
90
|
+
}
|
|
91
|
+
await input.seam.update(item, entry.before);
|
|
92
|
+
}
|
|
93
|
+
return { status: 'applied', spoken: undoText(entry, now, input.timeZone), itemId: entry.itemId };
|
|
94
|
+
} catch (error) {
|
|
95
|
+
log.stack.push(entry); // nothing changed: it can be tried again
|
|
96
|
+
return { status: 'failed', spoken: `I could not undo that: ${error instanceof Error ? error.message : 'the change did not go through'}.`, itemId: entry.itemId };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function executeVoiceActions(input: ExecuteInput): Promise<ExecuteOutcome> {
|
|
101
|
+
const now = (input.now ?? Date.now)();
|
|
102
|
+
const today = localDate(now, input.timeZone);
|
|
103
|
+
const nowIso = new Date(now).toISOString();
|
|
104
|
+
const log = await input.log.load();
|
|
105
|
+
const results: ActionResult[] = [];
|
|
106
|
+
let replayed = input.actions.length > 0;
|
|
107
|
+
|
|
108
|
+
for (const [n, action] of input.actions.entries()) {
|
|
109
|
+
const key = `${input.clientActionId}#${n}`;
|
|
110
|
+
const seen = log.applied[key];
|
|
111
|
+
if (seen) { results.push(seen); continue; }
|
|
112
|
+
replayed = false;
|
|
113
|
+
|
|
114
|
+
let result: ActionResult;
|
|
115
|
+
if (action.type === 'clarify') result = { status: 'asked', spoken: action.question };
|
|
116
|
+
else if (action.type === 'none') result = { status: 'asked', spoken: 'Sorry, I did not catch that. Can you say that again?' };
|
|
117
|
+
else if (action.type === 'undo') result = await undoOne(log, input, now);
|
|
118
|
+
else if (action.type === 'add_item') {
|
|
119
|
+
try {
|
|
120
|
+
const created = await input.seam.create({ title: action.title, ownerSub: input.ownerSub, dueAt: action.dueDate });
|
|
121
|
+
pushUndo(log, { actionId: key, kind: 'create', itemId: created.id, title: action.title, before: {}, after: {}, at: nowIso });
|
|
122
|
+
result = { status: 'applied', spoken: confirmText(action, action.title, now, input.timeZone), itemId: created.id };
|
|
123
|
+
} catch (error) {
|
|
124
|
+
result = { status: 'failed', spoken: `I could not add ${shortTitle(action.title)}.`, ...(error instanceof Error ? {} : {}) };
|
|
125
|
+
}
|
|
126
|
+
} else {
|
|
127
|
+
const patch = patchFor(action, today, nowIso) as ItemPatch;
|
|
128
|
+
let title = 'that item';
|
|
129
|
+
try {
|
|
130
|
+
const item = await input.seam.load(action.itemId);
|
|
131
|
+
if (!item) result = { status: 'failed', spoken: 'I could not find that item.', itemId: action.itemId };
|
|
132
|
+
else {
|
|
133
|
+
title = item.title;
|
|
134
|
+
const before = snapshot(item, patch);
|
|
135
|
+
await input.seam.update(item, patch);
|
|
136
|
+
pushUndo(log, { actionId: key, kind: 'edit', itemId: item.id, title: item.title, before, after: patch, at: nowIso });
|
|
137
|
+
result = { status: 'applied', spoken: confirmText(action, item.title, now, input.timeZone), itemId: item.id };
|
|
138
|
+
}
|
|
139
|
+
} catch {
|
|
140
|
+
result = { status: 'failed', spoken: `I could not update ${shortTitle(title)}.`, itemId: action.itemId };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
results.push(result);
|
|
145
|
+
// A failed write is not remembered, so a retry tries it again; everything else is.
|
|
146
|
+
if (result.status !== 'failed') remember(log, key, result);
|
|
147
|
+
await input.log.save(log);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const applied = results.filter((r) => r.status === 'applied').length;
|
|
151
|
+
const failed = results.filter((r) => r.status === 'failed').length;
|
|
152
|
+
return { results, text: results.map((r) => r.spoken).join(' '), applied, failed, undoDepth: log.stack.length, replayed };
|
|
153
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { executeVoiceActions } from './execute';
|
|
2
|
+
export type { ExecuteInput } from './execute';
|
|
3
|
+
export { commitmentEditSeam } from './seam';
|
|
4
|
+
export { createEntityActionLog, createMemoryActionLog, actionLogExternalId, ACTION_LOG_SOURCE, UNDO_DEPTH } from './log';
|
|
5
|
+
export { speakConfirmation, confirmText, undoText } from './confirm';
|
|
6
|
+
export type { SpokenConfirmation } from './confirm';
|
|
7
|
+
export type {
|
|
8
|
+
ActionLog, ActionLogStore, ActionResult, ActionStatus, EditableItem, ExecuteOutcome, ItemDraft, ItemEditSeam, ItemPatch, UndoEntry,
|
|
9
|
+
} from './types';
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the action log lives: ONE tenant row per person (a `source_document` with
|
|
3
|
+
* source `briefing_actions` and NO body/summary, so the to-do extractor reads
|
|
4
|
+
* nothing from it - the same trick as the briefing row, and no new entity type
|
|
5
|
+
* to declare). Owner scope is checked here as well as by the tenant.
|
|
6
|
+
*
|
|
7
|
+
* One row read-modified-written per reply: replies come from one person talking,
|
|
8
|
+
* one at a time. A lost update can only drop an undo entry or an idempotency key,
|
|
9
|
+
* never an item edit.
|
|
10
|
+
*/
|
|
11
|
+
import type { CorpusHttp } from '../../client';
|
|
12
|
+
import type { TenantEntity } from '../../entities';
|
|
13
|
+
import type { ActionLog, ActionLogStore } from './types';
|
|
14
|
+
|
|
15
|
+
export const ACTION_LOG_SOURCE = 'briefing_actions';
|
|
16
|
+
/** Undo depth, and how many applied ids are remembered for replay. */
|
|
17
|
+
export const UNDO_DEPTH = 5;
|
|
18
|
+
export const REMEMBERED_ACTIONS = 100;
|
|
19
|
+
|
|
20
|
+
export const emptyLog = (): ActionLog => ({ applied: {}, order: [], stack: [] });
|
|
21
|
+
|
|
22
|
+
export function createMemoryActionLog(initial: ActionLog = emptyLog()): ActionLogStore {
|
|
23
|
+
let log = initial;
|
|
24
|
+
return { async load() { return structuredClone(log); }, async save(next) { log = structuredClone(next); } };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const actionLogExternalId = (ownerSub: string) => `briefing-actions:${ownerSub}`;
|
|
28
|
+
|
|
29
|
+
type LogHttp = Pick<CorpusHttp, 'get'> & { post<T>(path: string, body?: unknown): Promise<T> };
|
|
30
|
+
|
|
31
|
+
export function createEntityActionLog(http: LogHttp, ownerSub: string): ActionLogStore {
|
|
32
|
+
const externalId = actionLogExternalId(ownerSub);
|
|
33
|
+
const mine = (entity: TenantEntity) => {
|
|
34
|
+
const sub = (entity as { owner_sub?: string }).owner_sub ?? (entity as { ownerSub?: string }).ownerSub
|
|
35
|
+
?? ((entity.data ?? {}) as Record<string, unknown>).owner_sub;
|
|
36
|
+
return sub === ownerSub;
|
|
37
|
+
};
|
|
38
|
+
return {
|
|
39
|
+
async load() {
|
|
40
|
+
const page = await http.get<{ results?: TenantEntity[] }>('api/v1/entities', {
|
|
41
|
+
params: { type: 'source_document', external_id__in: externalId, page_size: 5 },
|
|
42
|
+
});
|
|
43
|
+
const hit = (page.results ?? []).find((r) => (r.external_id ?? (r as { externalId?: string }).externalId) === externalId && mine(r));
|
|
44
|
+
const stored = ((hit?.data ?? {}) as Record<string, unknown>).action_log as Partial<ActionLog> | undefined;
|
|
45
|
+
return stored ? { applied: stored.applied ?? {}, order: stored.order ?? [], stack: stored.stack ?? [] } : emptyLog();
|
|
46
|
+
},
|
|
47
|
+
async save(log) {
|
|
48
|
+
await http.post('api/v1/entities/upsert', {
|
|
49
|
+
entity_type: 'source_document',
|
|
50
|
+
external_id: externalId,
|
|
51
|
+
name: 'Briefing actions',
|
|
52
|
+
data: {
|
|
53
|
+
title: 'Briefing actions',
|
|
54
|
+
source: ACTION_LOG_SOURCE,
|
|
55
|
+
source_label: 'Briefing',
|
|
56
|
+
source_ref: externalId,
|
|
57
|
+
owner_sub: ownerSub,
|
|
58
|
+
action_log: log,
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** The default seam: the planning client's own commitment verbs. No new write path. */
|
|
2
|
+
import type { CorpusHttp } from '../../client';
|
|
3
|
+
import { isRecord, notFound } from '../../client';
|
|
4
|
+
import { toCommitment } from '../../entities';
|
|
5
|
+
import type { Commitment, CommitmentApi, CorpusScope } from '../../types';
|
|
6
|
+
import type { EditableItem, ItemEditSeam } from './types';
|
|
7
|
+
|
|
8
|
+
export function commitmentEditSeam(options: {
|
|
9
|
+
api: Pick<CommitmentApi, 'updateCommitment' | 'createCommitment'>;
|
|
10
|
+
http: Pick<CorpusHttp, 'get'>;
|
|
11
|
+
scope: CorpusScope;
|
|
12
|
+
entitiesPath?: string;
|
|
13
|
+
}): ItemEditSeam {
|
|
14
|
+
const { api, http, scope } = options;
|
|
15
|
+
const entities = options.entitiesPath ?? 'api/v1/entities';
|
|
16
|
+
const raw = new WeakMap<EditableItem, Commitment>();
|
|
17
|
+
const wrap = (c: Commitment): EditableItem => {
|
|
18
|
+
const item: EditableItem = {
|
|
19
|
+
id: c.id, externalId: c.externalId, title: c.title, status: c.status, dueAt: c.dueAt ?? null,
|
|
20
|
+
...(c.priority !== undefined ? { priority: c.priority } : {}),
|
|
21
|
+
resolvedAt: c.resolvedAt ?? null, ...(c.statusReason ? { statusReason: c.statusReason } : {}),
|
|
22
|
+
};
|
|
23
|
+
raw.set(item, c);
|
|
24
|
+
return item;
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
async load(id) {
|
|
28
|
+
try {
|
|
29
|
+
const entity = await http.get<unknown>(`${entities}/${encodeURIComponent(id)}`);
|
|
30
|
+
if (!isRecord(entity, id)) throw notFound(id);
|
|
31
|
+
return wrap(toCommitment(entity, scope));
|
|
32
|
+
} catch (error) {
|
|
33
|
+
if ((error as { status?: number }).status === 404) return null;
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
async update(item, patch) {
|
|
38
|
+
if (!api.updateCommitment) throw new Error('This client cannot edit items.');
|
|
39
|
+
const row = raw.get(item) ?? ({ id: item.id, externalId: item.externalId } as Commitment);
|
|
40
|
+
if (!row.externalId) throw new Error('This item has no stable identity to edit.');
|
|
41
|
+
return wrap(await api.updateCommitment(row, patch as never));
|
|
42
|
+
},
|
|
43
|
+
async create(draft) {
|
|
44
|
+
if (!api.createCommitment) throw new Error('This client cannot add items.');
|
|
45
|
+
return wrap(await api.createCommitment({
|
|
46
|
+
title: draft.title, ownerSub: draft.ownerSub, ...(draft.dueAt ? { dueAt: draft.dueAt } : {}),
|
|
47
|
+
}));
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|