@startsimpli/integrations 0.2.124 → 0.2.125
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 +4 -4
- package/src/__tests__/briefing-intent-table.ts +121 -0
- package/src/__tests__/briefing-intent.test.ts +281 -0
- package/src/corpus/briefing/index.ts +1 -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
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** One line saying what was understood, shown BEFORE anything is applied. */
|
|
2
|
+
import { localDate } from '../compose';
|
|
3
|
+
import { speakable } from '../speak';
|
|
4
|
+
import { spokenWhen } from './dates';
|
|
5
|
+
import type { IntentContext, VoiceAction } from './types';
|
|
6
|
+
|
|
7
|
+
export const PRIORITY_NAMES = ['critical', 'urgent', 'medium', 'low', 'lowest'];
|
|
8
|
+
|
|
9
|
+
export function describeActions(actions: VoiceAction[], ctx: IntentContext): string {
|
|
10
|
+
const today = localDate(ctx.now, ctx.timeZone);
|
|
11
|
+
const titles = new Map([...ctx.briefed, ...ctx.open].map((i) => [i.id, speakable(i.title, 8)] as const));
|
|
12
|
+
const name = (id: string) => titles.get(id) ?? 'that item';
|
|
13
|
+
return actions.map((a) => {
|
|
14
|
+
switch (a.type) {
|
|
15
|
+
case 'defer': return `Move ${name(a.itemId)} to ${a.to === 'later' ? 'later' : a.label ?? spokenWhen(a.to, today)}`;
|
|
16
|
+
case 'pull_today': return `Pull ${name(a.itemId)} into today`;
|
|
17
|
+
case 'done': return `Mark ${name(a.itemId)} done`;
|
|
18
|
+
case 'drop': return `Drop ${name(a.itemId)}`;
|
|
19
|
+
case 'set_priority': return `Make ${name(a.itemId)} ${PRIORITY_NAMES[a.priority] ?? 'priority ' + a.priority}`;
|
|
20
|
+
case 'add_item': return `Add ${a.title}${a.dueDate ? ` for ${spokenWhen(a.dueDate, today)}` : ''}`;
|
|
21
|
+
case 'undo': return 'Undo the last change';
|
|
22
|
+
case 'clarify': return a.question;
|
|
23
|
+
default: return '';
|
|
24
|
+
}
|
|
25
|
+
}).filter(Boolean).join('. ');
|
|
26
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE DETERMINISTIC PARSER: the reply grammar that needs no model.
|
|
3
|
+
*
|
|
4
|
+
* It is the fallback when the model is down, slow or wrong, and it is also a
|
|
5
|
+
* check on the model's output (the same actions must be reachable from plain
|
|
6
|
+
* rules). It covers the verbs people actually say: done, later, tomorrow, today,
|
|
7
|
+
* drop, undo, move/push to a date, pull up to today, make it urgent, add X. A
|
|
8
|
+
* reply it cannot place gets a spoken "say that again", never a guess.
|
|
9
|
+
*
|
|
10
|
+
* ORDER MATTERS and is the file's contract: undo, add, priority, pull/defer,
|
|
11
|
+
* "do it today", done, drop, then a bare date ("next week") for the item being
|
|
12
|
+
* read. Several actions in one reply ("done with this, and move the next one to
|
|
13
|
+
* tomorrow") split at "and" ONLY where both halves are actions in their own right.
|
|
14
|
+
*/
|
|
15
|
+
import { localDate } from '../compose';
|
|
16
|
+
import { normalizeSpeech, splitWhen, type SpokenWhen } from './dates';
|
|
17
|
+
import { describeActions } from './describe';
|
|
18
|
+
import { contentWords } from './match';
|
|
19
|
+
import { resolveTarget } from './target';
|
|
20
|
+
import type { IntentContext, IntentResult, VoiceAction } from './types';
|
|
21
|
+
|
|
22
|
+
export const REPEAT_QUESTION = 'Sorry, I did not catch that. Can you say that again?';
|
|
23
|
+
|
|
24
|
+
const FILLER = /^(?:(?:hey|ok|okay|um|uh|so|well|actually|please|yeah|yes|alright|no wait|wait|oh|hmm|like|can you|could you|would you|will you|i want to|i would like to|i'd like to|let's|lets|i need you to|go ahead and|just|and|then|what about|how about)\b[,\s]*)+/;
|
|
25
|
+
/** ", I am not doing that today": a reason, not part of the instruction. */
|
|
26
|
+
const REASON = /(?<=\S)\s*[,;]\s*(?:because|since|cause|i(?:'m| am| can't| cannot| won't| will not| don't| do not| have no| already| just)\b|it's|it is|that's|that is|there's)\b.*$/;
|
|
27
|
+
const SPLIT = /\s*(?:,\s*)?\b(?:and then|and also|and|then|also|after that)\b\s+/;
|
|
28
|
+
|
|
29
|
+
const UNDO = /^(?:undo(?: that| it| the last(?: one| thing| change)?)?|never ?mind(?: that| it)?|cancel that|revert(?: that| it)?|take (?:that|it) back|scratch that|go back|put (?:it|that|them|this) back|reverse (?:that|it)|oops)$/;
|
|
30
|
+
const ADD = /^(?:add|create|new task|new to ?do|remind me to|remember to|note to self|don't let me forget to|dont let me forget to)\s+(.+)$/;
|
|
31
|
+
const PRIORITY_VERB = /\b(?:make|mark|set|flag|bump|change|label|put|rate|prioriti[sz]e)\b/;
|
|
32
|
+
const PULL_VERB = /\b(?:pull|bring)\b/;
|
|
33
|
+
const DEFER_VERB = /\b(?:move|push(?:ed)?|bump|postpone|delay|reschedule|snooze|defer|punt|shift|kick|slide|put off|put out|remind me (?:about|of))\b/;
|
|
34
|
+
const DO_TODAY = /^(?:i(?:'ll| will| am going to| gonna)? )?(?:do|work on|tackle|start|get to)\s+(.*?)\s*\b(?:today|tonight|now|this afternoon|this evening)$/;
|
|
35
|
+
const DONE_VERB = /\b(?:done|finished|finish|completed?|did|handled|sorted|wrapped up|knocked out|crossed off|cross off|checked off|check off)\b/;
|
|
36
|
+
const DROP_VERB = /\b(?:drop|delete|remove|cancel|scrap|ditch|kill|forget(?: about)?|get rid of|toss|trash|skip)\b/;
|
|
37
|
+
|
|
38
|
+
const LEVELS: Array<[RegExp, number]> = [
|
|
39
|
+
[/\b(?:lowest(?: priority)?|backlog|back burner)\b/, 4],
|
|
40
|
+
[/\b(?:critical|highest(?: priority)?|drop everything|p0)\b/, 0],
|
|
41
|
+
[/\b(?:urgent|high priority|top priority|important|asap|p1)\b/, 1],
|
|
42
|
+
[/\b(?:medium(?: priority)?|normal(?: priority)?|regular)\b/, 2],
|
|
43
|
+
[/\b(?:low priority|low|minor)\b/, 3],
|
|
44
|
+
];
|
|
45
|
+
const PRIORITY_NUMBER: Record<string, number> = { zero: 0, one: 1, two: 2, three: 3, four: 4, 0: 0, 1: 1, 2: 2, 3: 3, 4: 4 };
|
|
46
|
+
const PRIORITY_NUM_RE = /\bpriority (?:to |of |level )?(zero|one|two|three|four|[0-4])\b/;
|
|
47
|
+
|
|
48
|
+
type Pending = { actions: VoiceAction[] };
|
|
49
|
+
const ask = (question: string): VoiceAction => ({ type: 'clarify', question });
|
|
50
|
+
|
|
51
|
+
/** Does this clause hold an action of its own? (Decides where "and" splits.) */
|
|
52
|
+
function isAction(clause: string): boolean {
|
|
53
|
+
const n = normalizeSpeech(clause).replace(FILLER, '');
|
|
54
|
+
if (!n) return false;
|
|
55
|
+
return UNDO.test(n) || ADD.test(n) || DONE_VERB.test(n) || DROP_VERB.test(n) || PULL_VERB.test(n) || DEFER_VERB.test(n)
|
|
56
|
+
|| DO_TODAY.test(n) || (PRIORITY_VERB.test(n) && (LEVELS.some(([re]) => re.test(n)) || PRIORITY_NUM_RE.test(n)));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function clauses(raw: string): string[] {
|
|
60
|
+
const lead = normalizeSpeech(raw).replace(FILLER, '');
|
|
61
|
+
if (ADD.test(lead)) return [raw]; // "add buy salt and pepper": the "and" is part of the title
|
|
62
|
+
const parts = raw.split(SPLIT).filter((p) => p.trim());
|
|
63
|
+
const out: string[] = [];
|
|
64
|
+
for (const part of parts) {
|
|
65
|
+
const last = out[out.length - 1];
|
|
66
|
+
if (last !== undefined && isAction(last) && isAction(part)) out.push(part);
|
|
67
|
+
else if (last !== undefined) out[out.length - 1] = `${last} and ${part}`;
|
|
68
|
+
else out.push(part);
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const title = (s: string) => { const t = s.trim().replace(/[.,;:!?]+$/, ''); return t ? t[0].toUpperCase() + t.slice(1) : t; };
|
|
74
|
+
|
|
75
|
+
function parseClause(clause: string, ctx: IntentContext, reading: string | null): Pending | null {
|
|
76
|
+
const n = normalizeSpeech(clause.replace(REASON, '')).replace(FILLER, '').trim();
|
|
77
|
+
if (!n) return null;
|
|
78
|
+
const today = localDate(ctx.now, ctx.timeZone);
|
|
79
|
+
|
|
80
|
+
if (UNDO.test(n)) {
|
|
81
|
+
return { actions: [ctx.hasUndo ? { type: 'undo' } : ask('There is nothing to undo.')] };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const add = ADD.exec(n);
|
|
85
|
+
if (add) {
|
|
86
|
+
const body = add[1].replace(/^(?:a |an |the )?(?:new )?(?:task|to ?do|item|reminder)(?: to| called| named| for|:)?\s+/, '')
|
|
87
|
+
.replace(/\s+(?:to|on|in) (?:my|the) (?:list|to ?dos?|tasks?)$/, '');
|
|
88
|
+
const split = splitWhen(body, ctx.now, ctx.timeZone);
|
|
89
|
+
// A date only counts as the due date when it ends the sentence ("... for tomorrow"), not mid-title.
|
|
90
|
+
const dated = split !== null && split.after === '';
|
|
91
|
+
const text = title(dated && split ? split.rest : body);
|
|
92
|
+
if (!text) return { actions: [ask('What should I add?')] };
|
|
93
|
+
return { actions: [{ type: 'add_item', title: text, dueDate: dated && split && split.when.date ? split.when.date : null }] };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// PRIORITY
|
|
97
|
+
const level = LEVELS.find(([re]) => re.test(n));
|
|
98
|
+
const numbered = PRIORITY_NUM_RE.exec(n);
|
|
99
|
+
if ((PRIORITY_VERB.test(n) || numbered) && (level || numbered)) {
|
|
100
|
+
const priority = numbered ? PRIORITY_NUMBER[numbered[1]] : (level as [RegExp, number])[1];
|
|
101
|
+
const phrase = n.replace(numbered ? PRIORITY_NUM_RE : (level as [RegExp, number])[0], ' ')
|
|
102
|
+
.replace(/\b(?:make|mark|set|flag|bump|change|label|put|rate|prioriti[sz]e|as|to|priority|a|an|level|of|is|be|its|it's)\b/g, ' ');
|
|
103
|
+
const target = resolveTarget(phrase, ctx, reading);
|
|
104
|
+
if (!target.ok) return { actions: [ask(target.question)] };
|
|
105
|
+
return { actions: [{ type: 'set_priority', itemId: target.item.id, priority }] };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// PULL / DEFER with a date
|
|
109
|
+
const pull = PULL_VERB.test(n);
|
|
110
|
+
const defer = DEFER_VERB.test(n) || (/\bput\b/.test(n) && / (?:off|out)\b/.test(n));
|
|
111
|
+
if (pull || defer || (/\bput\b/.test(n) && splitWhen(n, ctx.now, ctx.timeZone))) {
|
|
112
|
+
const split = splitWhen(n, ctx.now, ctx.timeZone);
|
|
113
|
+
const phrase = (split ? split.rest : n)
|
|
114
|
+
.replace(/\b(?:move|pushed|push|bump|postpone|delay|reschedule|snooze|defer|punt|shift|kick|slide|put off|put out|put|pull|bring|remind me about|remind me of|out|up|off|back|into|to|for|until|till|it|them)\b/g, ' ');
|
|
115
|
+
const target = resolveTarget(phrase, ctx, reading);
|
|
116
|
+
if (!target.ok) return { actions: [ask(target.question)] };
|
|
117
|
+
let when: SpokenWhen | null = split ? split.when : null;
|
|
118
|
+
if (!when && /\bsnooze\b|\b(?:push|put) (?:it |this |that )?(?:out|off)\b/.test(n)) when = { date: null, later: true, label: 'later' };
|
|
119
|
+
if (!when && pull) when = { date: today, later: false, label: 'today' };
|
|
120
|
+
if (!when) return { actions: [ask('Move it to when?')] };
|
|
121
|
+
return { actions: [deferTo(target.item.id, when, today)] };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const doToday = DO_TODAY.exec(n);
|
|
125
|
+
if (doToday) {
|
|
126
|
+
const target = resolveTarget(doToday[1], ctx, reading);
|
|
127
|
+
if (!target.ok) return { actions: [ask(target.question)] };
|
|
128
|
+
return { actions: [{ type: 'pull_today', itemId: target.item.id, label: 'today' }] };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (DONE_VERB.test(n)) {
|
|
132
|
+
const phrase = n.replace(/\b(?:mark|as|is|are|was|been|has|have|i|ive|i've|already|just|with|done|finished|finish|completed?|did|handled|sorted|wrapped up|knocked out|crossed off|cross off|checked off|check off|off|its|it's|that's|thats)\b/g, ' ');
|
|
133
|
+
const target = resolveTarget(phrase, ctx, reading);
|
|
134
|
+
if (!target.ok) return { actions: [ask(target.question)] };
|
|
135
|
+
return { actions: [{ type: 'done', itemId: target.item.id }] };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (DROP_VERB.test(n)) {
|
|
139
|
+
const phrase = n.replace(/\b(?:drop|delete|remove|cancel|scrap|ditch|kill|forget about|forget|get rid of|toss|trash|skip|i|am|never|doing|just)\b/g, ' ');
|
|
140
|
+
const target = resolveTarget(phrase, ctx, reading);
|
|
141
|
+
if (!target.ok) return { actions: [ask(target.question)] };
|
|
142
|
+
return { actions: [{ type: 'drop', itemId: target.item.id }] };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// A bare date ("next week", "tomorrow", "not today") means: put the item being read there.
|
|
146
|
+
const bare = splitWhen(n, ctx.now, ctx.timeZone);
|
|
147
|
+
if (bare && !contentWords(bare.rest.replace(/\b(?:until|till|make|do|can|wait|will|should|be)\b/g, ' ')).length) {
|
|
148
|
+
const target = resolveTarget('', ctx, reading);
|
|
149
|
+
if (!target.ok) return { actions: [ask(target.question)] };
|
|
150
|
+
return { actions: [deferTo(target.item.id, bare.when, today)] };
|
|
151
|
+
}
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function deferTo(itemId: string, when: SpokenWhen, today: string): VoiceAction {
|
|
156
|
+
if (!when.later && when.date === today) return { type: 'pull_today', itemId, label: 'today' };
|
|
157
|
+
return { type: 'defer', itemId, to: when.later ? 'later' : (when.date as string), label: when.label };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function parseWithGrammar(ctx: IntentContext): IntentResult {
|
|
161
|
+
const raw = ctx.utterance.toLowerCase().replace(/[‘’]/g, "'").trim();
|
|
162
|
+
const actions: VoiceAction[] = [];
|
|
163
|
+
let reading = ctx.readingId;
|
|
164
|
+
for (const clause of clauses(raw)) {
|
|
165
|
+
const parsed = parseClause(clause, ctx, reading);
|
|
166
|
+
if (!parsed) {
|
|
167
|
+
if (!actions.length) actions.push(ask(REPEAT_QUESTION));
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
actions.push(...parsed.actions);
|
|
171
|
+
if (parsed.actions.some((a) => a.type === 'clarify')) break; // act on what was clear, ask about the rest
|
|
172
|
+
}
|
|
173
|
+
const final = actions.length ? actions : [ask(REPEAT_QUESTION)];
|
|
174
|
+
return { actions: final, source: 'grammar', understood: describeActions(final, ctx), notes: [] };
|
|
175
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GROUNDING: is each item the model picked one the person actually pointed at?
|
|
3
|
+
*
|
|
4
|
+
* A small model acts when it should ask: with nothing being read it defers the
|
|
5
|
+
* first item on "later", or every item; it takes "pull" in "pull it up" for
|
|
6
|
+
* "pull request". So an action is kept only when its item is
|
|
7
|
+
* - the item being read, and the reply names no other item; or
|
|
8
|
+
* - the one the words describe (title, project or ticket code), uniquely; or
|
|
9
|
+
* - what "the next / previous / third / other one" structurally means.
|
|
10
|
+
* Anything else is a guess, and a guess becomes the grammar's spoken question.
|
|
11
|
+
*/
|
|
12
|
+
import { localDate } from '../compose';
|
|
13
|
+
import { splitWhen } from './dates';
|
|
14
|
+
import { contentWords, words } from './match';
|
|
15
|
+
import type { IntentContext, IntentItem, VoiceAction } from './types';
|
|
16
|
+
|
|
17
|
+
/** Words that are the instruction, not the description of an item. */
|
|
18
|
+
const COMMAND = new Set(['move', 'push', 'pull', 'bring', 'mark', 'make', 'set', 'flag', 'done', 'drop', 'delete', 'remove',
|
|
19
|
+
'cancel', 'scrap', 'finish', 'finished', 'complete', 'completed', 'snooze', 'delay', 'postpone', 'defer', 'reschedule',
|
|
20
|
+
'later', 'today', 'tomorrow', 'tonight', 'week', 'weekend', 'month', 'day', 'days', 'weeks', 'next', 'monday', 'tuesday',
|
|
21
|
+
'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'priority', 'urgent', 'critical', 'low', 'lowest', 'high',
|
|
22
|
+
'medium', 'important', 'undo', 'add', 'remind', 'forget', 'kill', 'hold', 'wait', 'yeah', 'actually', 'okay', 'ok',
|
|
23
|
+
'complete', 'finish', 'bump', 'shift', 'put', 'get', 'rid', 'doing', 'never', 'want', 'dont', 'first', 'second', 'third',
|
|
24
|
+
'fourth', 'fifth', 'previous', 'last', 'january', 'february', 'march', 'april', 'june', 'july', 'august', 'september',
|
|
25
|
+
'october', 'november', 'december', 'sometime', 'time', 'tmrw', 'asap']);
|
|
26
|
+
|
|
27
|
+
const same = (a: string, b: string) => a === b || (a.length >= 4 && b.length >= 4 && a.slice(0, 4) === b.slice(0, 4));
|
|
28
|
+
const ORDINALS: Record<string, number> = { first: 1, second: 2, third: 3, fourth: 4, fifth: 5, sixth: 6, seventh: 7, eighth: 8 };
|
|
29
|
+
|
|
30
|
+
/** How many of the person's descriptive words fit this item (title 1, project 0.6, ticket code 1). */
|
|
31
|
+
function fit(spoken: string[], item: IntentItem): number {
|
|
32
|
+
const title = contentWords(item.title);
|
|
33
|
+
const focus = contentWords(item.focusName ?? '');
|
|
34
|
+
const code = words(item.linearIdentifier ?? '');
|
|
35
|
+
let sum = 0;
|
|
36
|
+
for (const w of spoken) {
|
|
37
|
+
if (title.some((t) => same(t, w)) || code.includes(w)) sum += 1;
|
|
38
|
+
else if (focus.some((f) => same(f, w))) sum += 0.6;
|
|
39
|
+
}
|
|
40
|
+
return sum;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** null when every item is grounded; otherwise why not. */
|
|
44
|
+
export function ungrounded(actions: VoiceAction[], ctx: IntentContext): string | null {
|
|
45
|
+
// A move needs a date in the reply (or a word that means "later"); a model that supplies one is guessing.
|
|
46
|
+
const said = splitWhen(ctx.utterance, ctx.now, ctx.timeZone);
|
|
47
|
+
const dated = said !== null;
|
|
48
|
+
const laterWord = /\b(?:snooze|postpone|delay|defer|can wait|could wait|let it wait|put off|hold off|push (?:it |this |that )?out|punt|kick)\b/i.test(ctx.utterance);
|
|
49
|
+
for (const a of actions) {
|
|
50
|
+
if (a.type === 'defer' && !dated && !(a.to === 'later' && laterWord)) return 'no date was said';
|
|
51
|
+
// The date the model chose must be the date the words say.
|
|
52
|
+
if (a.type === 'defer' && said && (said.when.later ? 'later' : said.when.date) !== a.to) return 'the date disagrees with the words';
|
|
53
|
+
if (a.type === 'pull_today' && said && !said.when.later && said.when.date !== localDate(ctx.now, ctx.timeZone)) return 'the date disagrees with the words';
|
|
54
|
+
}
|
|
55
|
+
const targeted = actions.filter((a): a is Extract<VoiceAction, { itemId: string }> => 'itemId' in a);
|
|
56
|
+
if (!targeted.length) return null;
|
|
57
|
+
const all = [...ctx.briefed, ...ctx.open.filter((o) => !ctx.briefed.some((b) => b.id === o.id))];
|
|
58
|
+
const text = words(ctx.utterance);
|
|
59
|
+
const spoken = text.filter((w) => contentWords(w).length && !COMMAND.has(w));
|
|
60
|
+
const idx = ctx.readingId ? ctx.briefed.findIndex((i) => i.id === ctx.readingId) : -1;
|
|
61
|
+
const briefedIds = new Set(ctx.briefed.map((i) => i.id));
|
|
62
|
+
|
|
63
|
+
const structural = new Set<string>();
|
|
64
|
+
const asks = (w: string) => new RegExp(`\\b${w} (?:one|item|thing|task)\\b`).test(ctx.utterance.toLowerCase());
|
|
65
|
+
if (asks('next') && idx >= 0 && ctx.briefed[idx + 1]) structural.add(ctx.briefed[idx + 1].id);
|
|
66
|
+
if ((asks('previous') || asks('one before')) && idx > 0) structural.add(ctx.briefed[idx - 1].id);
|
|
67
|
+
if (asks('last')) structural.add(ctx.briefed[ctx.briefed.length - 1]?.id ?? '');
|
|
68
|
+
for (const w of text) if (ORDINALS[w] && /\b(?:one|item|thing)\b/.test(ctx.utterance.toLowerCase()) && ctx.briefed[ORDINALS[w] - 1]) structural.add(ctx.briefed[ORDINALS[w] - 1].id);
|
|
69
|
+
const other = asks('other');
|
|
70
|
+
const deictic = /\b(?:this|that|it|these|those)\b/.test(ctx.utterance.toLowerCase());
|
|
71
|
+
|
|
72
|
+
const scored = all.map((item) => ({ item, fit: fit(spoken, item) })).filter((s) => s.fit > 0);
|
|
73
|
+
const top = scored.length ? Math.max(...scored.map((s) => s.fit)) : 0;
|
|
74
|
+
const best = scored.filter((s) => s.fit >= top - 1e-9).map((s) => s.item.id);
|
|
75
|
+
const targetedIds = new Set(targeted.map((a) => a.itemId));
|
|
76
|
+
|
|
77
|
+
for (const a of targeted) {
|
|
78
|
+
const id = a.itemId;
|
|
79
|
+
if (structural.has(id)) continue;
|
|
80
|
+
if (other && !briefedIds.has(id)) {
|
|
81
|
+
if (ctx.open.filter((o) => !briefedIds.has(o.id)).length > 1 && !scored.some((s) => s.item.id === id)) return `"${id}" is a guess among several other items`;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (scored.length) {
|
|
85
|
+
if (!scored.some((s) => s.item.id === id)) return `"${id}" is not what the words describe`;
|
|
86
|
+
if (best.length > 1 && best.includes(id) && !best.every((b) => targetedIds.has(b))) return 'the words fit several items equally';
|
|
87
|
+
if (targeted.length === 1 && !best.includes(id)) return `"${id}" fits worse than another item`;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (id === ctx.readingId && (deictic || !(structural.size || other))) continue;
|
|
91
|
+
if (structural.size || other) return `"${id}" is not the next/previous/other item`;
|
|
92
|
+
if (id !== ctx.readingId) return ctx.readingId ? `"${id}" is not the item being read` : 'nothing is being read';
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { resolveVoiceIntent } from './resolve';
|
|
2
|
+
export { parseWithGrammar, REPEAT_QUESTION } from './grammar';
|
|
3
|
+
export { parseWhen, splitWhen, spokenWhen, isIsoDate, addDays } from './dates';
|
|
4
|
+
export type { SpokenWhen } from './dates';
|
|
5
|
+
export { readingAt, charPositionOf, CHARS_PER_SECOND } from './position';
|
|
6
|
+
export type { PlaybackPosition } from './position';
|
|
7
|
+
export { describeActions, PRIORITY_NAMES } from './describe';
|
|
8
|
+
export { intentPrompt, intentSystemPrompt, checkModelReply } from './model';
|
|
9
|
+
export { matchItems, scoreItems } from './match';
|
|
10
|
+
export { resolveTarget, whichOne } from './target';
|
|
11
|
+
export type { IntentContext, IntentItem, IntentOptions, IntentResult, VoiceAction } from './types';
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fuzzy match of a spoken description ("the bench one", "the dentist thing")
|
|
3
|
+
* against item titles, focus names and ticket codes. Deterministic, no model.
|
|
4
|
+
*
|
|
5
|
+
* A word matches when equal or when both share a 4+ letter stem (print/printer,
|
|
6
|
+
* flight/flights). The score is the share of the SPOKEN words found, so a short
|
|
7
|
+
* description that fits one item scores 1, and two items that fit equally tie,
|
|
8
|
+
* which is what makes it ambiguous rather than a guess.
|
|
9
|
+
*/
|
|
10
|
+
import type { IntentItem } from './types';
|
|
11
|
+
|
|
12
|
+
const STOP = new Set(['the', 'a', 'an', 'to', 'of', 'for', 'and', 'my', 'with', 'about', 'up', 'on', 'in', 'at', 'it',
|
|
13
|
+
'that', 'this', 'one', 'thing', 'things', 'item', 'task', 'todo', 'other', 'please', 'out', 'i', 'is', 'are', 'was',
|
|
14
|
+
'be', 'as', 'its', 'mine', 'those', 'these', 'back', 'off', 'into', 'from', 'but', 'then', 'now', 'just', 'also',
|
|
15
|
+
'you', 'we', 'me', 'do']);
|
|
16
|
+
|
|
17
|
+
export const words = (text: string): string[] =>
|
|
18
|
+
text.toLowerCase().replace(/['’]/g, '').split(/[^a-z0-9]+/).filter(Boolean);
|
|
19
|
+
|
|
20
|
+
/** The content words of a description: what is left after the filler. */
|
|
21
|
+
export const contentWords = (text: string): string[] => words(text).filter((w) => !STOP.has(w));
|
|
22
|
+
|
|
23
|
+
const same = (a: string, b: string) => a === b || (a.length >= 4 && b.length >= 4 && (a.startsWith(b.slice(0, 4)) && b.startsWith(a.slice(0, 4))));
|
|
24
|
+
|
|
25
|
+
export interface Scored { item: IntentItem; score: number }
|
|
26
|
+
|
|
27
|
+
export function scoreItems(query: string, items: IntentItem[]): Scored[] {
|
|
28
|
+
const q = contentWords(query);
|
|
29
|
+
if (!q.length) return [];
|
|
30
|
+
return items.map((item) => {
|
|
31
|
+
const title = contentWords(item.title);
|
|
32
|
+
const focus = contentWords(item.focusName ?? '');
|
|
33
|
+
const code = (item.linearIdentifier ?? '').toLowerCase();
|
|
34
|
+
let sum = 0;
|
|
35
|
+
for (const w of q) {
|
|
36
|
+
if (title.some((t) => same(t, w))) sum += 1;
|
|
37
|
+
else if (code && words(code).includes(w)) sum += 1;
|
|
38
|
+
else if (focus.some((f) => same(f, w))) sum += 0.6;
|
|
39
|
+
}
|
|
40
|
+
return { item, score: sum / q.length };
|
|
41
|
+
}).filter((s) => s.score >= 0.5);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export type Match =
|
|
45
|
+
| { kind: 'one'; item: IntentItem }
|
|
46
|
+
| { kind: 'many'; items: IntentItem[] }
|
|
47
|
+
| { kind: 'none' };
|
|
48
|
+
|
|
49
|
+
/** The best item for a description, several when they tie, none when nothing fits. */
|
|
50
|
+
export function matchItems(query: string, items: IntentItem[]): Match {
|
|
51
|
+
const scored = scoreItems(query, items).sort((a, b) => b.score - a.score);
|
|
52
|
+
if (!scored.length) return { kind: 'none' };
|
|
53
|
+
const top = scored[0].score;
|
|
54
|
+
const tied = scored.filter((s) => s.score >= top - 1e-9);
|
|
55
|
+
return tied.length === 1 ? { kind: 'one', item: tied[0].item } : { kind: 'many', items: tied.map((s) => s.item) };
|
|
56
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The model half of intent parsing: the prompt, and the CHECK of what comes back.
|
|
3
|
+
*
|
|
4
|
+
* The model proposes; this decides. Every item id must be one the person could
|
|
5
|
+
* have meant (the spoken list or an open item), dates must be real, priorities
|
|
6
|
+
* 0-4; one bad action rejects the whole answer and the grammar answers instead.
|
|
7
|
+
*/
|
|
8
|
+
import { localDate } from '../compose';
|
|
9
|
+
import { speakable } from '../speak';
|
|
10
|
+
import { isIsoDate, parseWhen, spokenWhen, weekdayName } from './dates';
|
|
11
|
+
import { PRIORITY_NAMES } from './describe';
|
|
12
|
+
import type { IntentContext, IntentItem, VoiceAction } from './types';
|
|
13
|
+
|
|
14
|
+
export const MAX_ACTIONS = 5;
|
|
15
|
+
const MAX_OPEN_SHOWN = 40;
|
|
16
|
+
|
|
17
|
+
export function intentSystemPrompt(): string {
|
|
18
|
+
return [
|
|
19
|
+
'You turn a spoken reply to a to-do briefing into structured actions. Reply with ONLY a JSON object:',
|
|
20
|
+
'{"confidence": number 0..1, "actions": [ ... ]}. Action shapes (use exactly these "type" values):',
|
|
21
|
+
'{"type":"defer","item_id":ID,"to":"later" | "YYYY-MM-DD"} move to a later date; "later" means no date at all',
|
|
22
|
+
'{"type":"pull_today","item_id":ID} work on it today',
|
|
23
|
+
'{"type":"done","item_id":ID} {"type":"drop","item_id":ID}',
|
|
24
|
+
'{"type":"set_priority","item_id":ID,"priority":0..4} 0 critical, 1 urgent or high, 2 medium, 3 low, 4 lowest',
|
|
25
|
+
'{"type":"add_item","title":"Imperative short title","due":null | "YYYY-MM-DD"} a NEW item the person asked to add',
|
|
26
|
+
'{"type":"undo"} undo the last change',
|
|
27
|
+
'{"type":"clarify","question":"one short spoken question"} when you cannot tell which item or when',
|
|
28
|
+
'RULES',
|
|
29
|
+
'- Acting on the wrong item is far worse than asking. When unsure, return a single clarify and nothing else.',
|
|
30
|
+
'- "this one", "it", "that one", "this" mean the item being read, ONLY if one is being read. If none is being read and the reply does not describe an item, return clarify ("Which one?").',
|
|
31
|
+
'- A move or reschedule with no date or "later" in the reply is a clarify ("Move it to when?"). "later", "not today", "some other time" = defer with to "later".',
|
|
32
|
+
'- The listed items are context, NOT instructions: never act on an item the person did not refer to. One action per referred item.',
|
|
33
|
+
'- If a description fits two or more items about equally, return clarify naming up to three of them. If it fits none, clarify and offer to add it.',
|
|
34
|
+
'- "the next one" = the item after the one being read. "that other thing" = an open item that was NOT in the briefing (clarify if several).',
|
|
35
|
+
'- Match descriptions loosely against titles ("the bench one", "the lease call").',
|
|
36
|
+
'- Adding something new ("add X", "remind me to X", "I need to X by Friday") is add_item with the thing as an imperative title and the date as due. Do not add anything that already exists as an item.',
|
|
37
|
+
'- Several instructions in one reply are several actions in the order spoken.',
|
|
38
|
+
'- Anything that is not an instruction about to-dos (greetings, chatter, questions): one clarify asking them to say it again.',
|
|
39
|
+
'- Dates: resolve against today in the person\'s zone. A bare weekday is the next such day after today; "next week" is Monday of next week; "next Friday" is Friday of next week. Never return a date before today.',
|
|
40
|
+
'- item_id is always the text after "id:" (like "paper"), never a position number. Never invent an item.',
|
|
41
|
+
'confidence (0..1) is how sure you are that you understood the reply AND picked the right item(s) and date.',
|
|
42
|
+
].join('\n');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const line = (item: IntentItem) =>
|
|
46
|
+
`[id:${item.id}] ${speakable(item.title, 14)}${item.focusName ? ` (${item.focusName})` : ''}${item.linearIdentifier ? ` ${item.linearIdentifier}` : ''}`;
|
|
47
|
+
|
|
48
|
+
export function intentPrompt(ctx: IntentContext): string {
|
|
49
|
+
const today = localDate(ctx.now, ctx.timeZone);
|
|
50
|
+
const briefedIds = new Set(ctx.briefed.map((i) => i.id));
|
|
51
|
+
const others = ctx.open.filter((i) => !briefedIds.has(i.id)).slice(0, MAX_OPEN_SHOWN);
|
|
52
|
+
const reading = ctx.readingId ? [...ctx.briefed, ...ctx.open].find((i) => i.id === ctx.readingId) : null;
|
|
53
|
+
return [
|
|
54
|
+
`Today is ${weekdayName(today)} ${today} (${ctx.timeZone}).`,
|
|
55
|
+
'Items just spoken, in order:',
|
|
56
|
+
...(ctx.briefed.length ? ctx.briefed.map((i, n) => `spoken #${n + 1}: ${line(i)}`) : ['(none)']),
|
|
57
|
+
`Item being read when the person spoke: ${reading ? line(reading) : 'none (playback was not on an item)'}`,
|
|
58
|
+
'Other open items (not in the briefing):',
|
|
59
|
+
...(others.length ? others.map((i) => `- ${line(i)}`) : ['(none)']),
|
|
60
|
+
`Undo available: ${ctx.hasUndo ? 'yes' : 'no'}`,
|
|
61
|
+
`The person said: ${JSON.stringify(ctx.utterance)}`,
|
|
62
|
+
].join('\n');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export type Checked = { ok: true; actions: VoiceAction[]; confidence: number } | { ok: false; reason: string };
|
|
66
|
+
|
|
67
|
+
function parseJson(text: string): unknown {
|
|
68
|
+
const body = text.trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
|
|
69
|
+
try { return JSON.parse(body); } catch { /* try the outermost braces */ }
|
|
70
|
+
const a = body.indexOf('{'); const b = body.lastIndexOf('}');
|
|
71
|
+
if (a < 0 || b <= a) return undefined;
|
|
72
|
+
try { return JSON.parse(body.slice(a, b + 1)); } catch { return undefined; }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function checkModelReply(reply: string, ctx: IntentContext): Checked {
|
|
76
|
+
const data = parseJson(reply) as { confidence?: unknown; actions?: unknown } | undefined;
|
|
77
|
+
if (!data || typeof data !== 'object') return { ok: false, reason: 'reply was not JSON' };
|
|
78
|
+
if (typeof data.confidence !== 'number' || data.confidence < 0 || data.confidence > 1) return { ok: false, reason: 'missing confidence' };
|
|
79
|
+
if (!Array.isArray(data.actions) || !data.actions.length || data.actions.length > MAX_ACTIONS) return { ok: false, reason: 'no usable actions' };
|
|
80
|
+
const today = localDate(ctx.now, ctx.timeZone);
|
|
81
|
+
const known = new Set([...ctx.briefed, ...ctx.open].map((i) => i.id));
|
|
82
|
+
const out: VoiceAction[] = [];
|
|
83
|
+
|
|
84
|
+
for (const raw of data.actions as Array<Record<string, unknown>>) {
|
|
85
|
+
if (!raw || typeof raw !== 'object') return { ok: false, reason: 'action is not an object' };
|
|
86
|
+
const type = raw.type;
|
|
87
|
+
const id = typeof raw.item_id === 'string' ? raw.item_id : '';
|
|
88
|
+
const needsItem = ['defer', 'pull_today', 'done', 'drop', 'set_priority'].includes(String(type));
|
|
89
|
+
if (needsItem && !known.has(id)) return { ok: false, reason: `unknown item ${JSON.stringify(raw.item_id)}` };
|
|
90
|
+
switch (type) {
|
|
91
|
+
case 'defer': {
|
|
92
|
+
const when = typeof raw.to === 'string' ? (raw.to === 'later' ? 'later' : isIsoDate(raw.to) ? raw.to : parseWhen(raw.to, ctx.now, ctx.timeZone)) : null;
|
|
93
|
+
if (!when) return { ok: false, reason: 'unusable date' };
|
|
94
|
+
const date = typeof when === 'string' ? when : when.later ? 'later' : when.date;
|
|
95
|
+
if (!date) return { ok: false, reason: 'unusable date' };
|
|
96
|
+
if (date !== 'later' && date < today) return { ok: false, reason: 'date is in the past' };
|
|
97
|
+
if (date === today) { out.push({ type: 'pull_today', itemId: id, label: 'today' }); break; }
|
|
98
|
+
out.push({ type: 'defer', itemId: id, to: date, label: date === 'later' ? 'later' : spokenWhen(date, today) });
|
|
99
|
+
break;
|
|
100
|
+
}
|
|
101
|
+
case 'pull_today': out.push({ type: 'pull_today', itemId: id, label: 'today' }); break;
|
|
102
|
+
case 'done': case 'drop': out.push({ type, itemId: id }); break;
|
|
103
|
+
case 'set_priority': {
|
|
104
|
+
const p = raw.priority;
|
|
105
|
+
if (typeof p !== 'number' || !Number.isInteger(p) || p < 0 || p >= PRIORITY_NAMES.length) return { ok: false, reason: 'bad priority' };
|
|
106
|
+
out.push({ type: 'set_priority', itemId: id, priority: p });
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
case 'add_item': {
|
|
110
|
+
const t = typeof raw.title === 'string' ? raw.title.trim() : '';
|
|
111
|
+
if (!t || t.length > 200) return { ok: false, reason: 'bad title' };
|
|
112
|
+
let due: string | null = null;
|
|
113
|
+
if (typeof raw.due === 'string' && raw.due) {
|
|
114
|
+
const w = isIsoDate(raw.due) ? raw.due : parseWhen(raw.due, ctx.now, ctx.timeZone)?.date;
|
|
115
|
+
if (!w) return { ok: false, reason: 'unusable due date' };
|
|
116
|
+
if (w < today) return { ok: false, reason: 'due date is in the past' };
|
|
117
|
+
due = w;
|
|
118
|
+
}
|
|
119
|
+
out.push({ type: 'add_item', title: t[0].toUpperCase() + t.slice(1), dueDate: due });
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
case 'undo': out.push({ type: 'undo' }); break;
|
|
123
|
+
case 'clarify': {
|
|
124
|
+
const q = typeof raw.question === 'string' ? raw.question.trim() : '';
|
|
125
|
+
if (!q) return { ok: false, reason: 'empty question' };
|
|
126
|
+
out.push({ type: 'clarify', question: q });
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
case 'none': out.push({ type: 'clarify', question: 'Sorry, I did not catch that. Can you say that again?' }); break;
|
|
130
|
+
default: return { ok: false, reason: `unknown action type ${JSON.stringify(type)}` };
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (out.some((a) => a.type === 'undo') && !ctx.hasUndo) return { ok: true, actions: [{ type: 'clarify', question: 'There is nothing to undo.' }], confidence: data.confidence };
|
|
134
|
+
return { ok: true, actions: out, confidence: data.confidence };
|
|
135
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* "This one": the item being read when the person pressed talk.
|
|
3
|
+
*
|
|
4
|
+
* The briefing stores where each item's sentence sits in the text (`offsets`).
|
|
5
|
+
* ElevenLabs gives character timing; OpenAI does not, so with no timing the
|
|
6
|
+
* position is ESTIMATED from seconds played at ~15 characters a second (the rate
|
|
7
|
+
* measured on gpt-4o-mini-tts), or from the fraction played when the audio's
|
|
8
|
+
* length is known (which is exact enough for a constant-pace voice).
|
|
9
|
+
*
|
|
10
|
+
* Rule when playback sits BETWEEN items (a pause, the greeting between): the last
|
|
11
|
+
* fully spoken item. Before the first item's sentence: nobody, and the reply must
|
|
12
|
+
* name its item.
|
|
13
|
+
*/
|
|
14
|
+
import type { BriefingContextRecord } from '../store';
|
|
15
|
+
|
|
16
|
+
export const CHARS_PER_SECOND = 15;
|
|
17
|
+
|
|
18
|
+
export interface PlaybackPosition {
|
|
19
|
+
/** Exact character position, when the provider gave word timing. */
|
|
20
|
+
charPosition?: number;
|
|
21
|
+
/** Seconds played so far. */
|
|
22
|
+
seconds?: number;
|
|
23
|
+
/** Total audio length, when known. */
|
|
24
|
+
durationSeconds?: number;
|
|
25
|
+
/** Length of the spoken text, needed with `durationSeconds`. */
|
|
26
|
+
textLength?: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function charPositionOf(position: PlaybackPosition): number {
|
|
30
|
+
if (position.charPosition !== undefined) return position.charPosition;
|
|
31
|
+
const seconds = position.seconds ?? 0;
|
|
32
|
+
if (position.durationSeconds && position.textLength) {
|
|
33
|
+
return (Math.min(seconds, position.durationSeconds) / position.durationSeconds) * position.textLength;
|
|
34
|
+
}
|
|
35
|
+
return seconds * CHARS_PER_SECOND;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function readingAt(
|
|
39
|
+
context: Pick<BriefingContextRecord, 'offsets'>,
|
|
40
|
+
position: PlaybackPosition,
|
|
41
|
+
): string | null {
|
|
42
|
+
const at = charPositionOf(position);
|
|
43
|
+
let last: string | null = null;
|
|
44
|
+
for (const segment of [...context.offsets].sort((a, b) => a.start - b.start)) {
|
|
45
|
+
if (at >= segment.start && at <= segment.end) return segment.id;
|
|
46
|
+
if (segment.end < at) last = segment.id;
|
|
47
|
+
}
|
|
48
|
+
return last;
|
|
49
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* resolveVoiceIntent: utterance + the list just spoken -> actions.
|
|
3
|
+
*
|
|
4
|
+
* Model first (it handles loose wording), checked; the grammar answers whenever
|
|
5
|
+
* the model is absent, late, malformed, names an item that does not exist, or
|
|
6
|
+
* contradicts the data. A low-confidence model answer asks instead of acting.
|
|
7
|
+
* NEVER executes anything.
|
|
8
|
+
*/
|
|
9
|
+
import { describeActions } from './describe';
|
|
10
|
+
import { parseWithGrammar } from './grammar';
|
|
11
|
+
import { ungrounded } from './ground';
|
|
12
|
+
import { checkModelReply, intentPrompt, intentSystemPrompt } from './model';
|
|
13
|
+
import type { IntentContext, IntentOptions, IntentResult } from './types';
|
|
14
|
+
|
|
15
|
+
const DEFAULT_TIMEOUT_MS = 8_000;
|
|
16
|
+
const DEFAULT_MIN_CONFIDENCE = 0.6;
|
|
17
|
+
|
|
18
|
+
export async function resolveVoiceIntent(ctx: IntentContext, options: IntentOptions = {}): Promise<IntentResult> {
|
|
19
|
+
const notes: string[] = [];
|
|
20
|
+
if (!ctx.utterance.trim()) return { ...parseWithGrammar(ctx), notes: ['empty utterance'] };
|
|
21
|
+
|
|
22
|
+
if (options.llm) {
|
|
23
|
+
try {
|
|
24
|
+
const reply = await options.llm.write({
|
|
25
|
+
system: intentSystemPrompt(),
|
|
26
|
+
prompt: intentPrompt(ctx),
|
|
27
|
+
timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
28
|
+
});
|
|
29
|
+
const checked = checkModelReply(reply, ctx);
|
|
30
|
+
if (!checked.ok) notes.push(checked.reason);
|
|
31
|
+
else {
|
|
32
|
+
const guess = ungrounded(checked.actions, ctx);
|
|
33
|
+
if (guess) notes.push(`ungrounded: ${guess}`);
|
|
34
|
+
else if (checked.actions.every((a) => a.type === 'clarify') && parseWithGrammar(ctx).actions.some((a) => a.type !== 'clarify')) {
|
|
35
|
+
// The model hedged where the plain rules are sure (they only act on a unique, named match).
|
|
36
|
+
notes.push('model asked; the grammar found a clear match');
|
|
37
|
+
} else if (checked.confidence < (options.minConfidence ?? DEFAULT_MIN_CONFIDENCE)) {
|
|
38
|
+
const actions = [{ type: 'clarify' as const, question: 'I am not sure I got that. Can you say that again?' }];
|
|
39
|
+
return { actions, source: 'llm', understood: describeActions(actions, ctx), notes: [`low confidence ${checked.confidence}`] };
|
|
40
|
+
} else {
|
|
41
|
+
return { actions: checked.actions, source: 'llm', understood: describeActions(checked.actions, ctx), notes };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
} catch (error) {
|
|
45
|
+
notes.push(`model failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return { ...parseWithGrammar(ctx), notes };
|
|
49
|
+
}
|