@startsimpli/integrations 0.2.145 → 0.2.147
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 +2 -0
- package/src/__tests__/briefing-reply.test.ts +334 -0
- package/src/__tests__/corpus-tracker.test.tsx +79 -0
- package/src/__tests__/extract-classify.test.ts +9 -4
- package/src/__tests__/owner-backfill.test.ts +114 -0
- package/src/__tests__/owner-link.test.ts +115 -0
- package/src/__tests__/owner-picker.test.tsx +70 -0
- package/src/__tests__/private-items.test.ts +63 -0
- package/src/__tests__/roster.test.ts +27 -0
- package/src/__tests__/task-detail-private.test.tsx +44 -0
- package/src/__tests__/tracker-sort.test.ts +28 -0
- package/src/components/index.ts +1 -0
- package/src/components/pages/TaskDetailPage.tsx +51 -2
- package/src/components/pages/TrackerPage.tsx +28 -6
- package/src/components/pages/task-tracker/OwnerPicker.tsx +82 -0
- package/src/components/pages/tracker/TrackerBoard.tsx +45 -0
- package/src/components/pages/tracker/TrackerToolbar.tsx +44 -0
- package/src/corpus/briefing/actions/execute.ts +5 -4
- package/src/corpus/briefing/actions/log.ts +1 -1
- package/src/corpus/briefing/actions/types.ts +21 -0
- package/src/corpus/briefing/index.ts +1 -0
- package/src/corpus/briefing/intent/model.ts +3 -0
- package/src/corpus/briefing/intent/resolve.ts +14 -6
- package/src/corpus/briefing/intent/types.ts +7 -0
- package/src/corpus/briefing/reply/handle.ts +174 -0
- package/src/corpus/briefing/reply/index.ts +6 -0
- package/src/corpus/briefing/reply/respond.ts +95 -0
- package/src/corpus/briefing/reply/types.ts +112 -0
- package/src/corpus/briefing/store.ts +14 -0
- package/src/corpus/client.ts +24 -18
- package/src/corpus/entities.ts +7 -0
- package/src/corpus/extract.ts +21 -0
- package/src/corpus/index.ts +4 -0
- package/src/corpus/owner-backfill.ts +200 -0
- package/src/corpus/owner-link.ts +160 -0
- package/src/corpus/roster.ts +53 -0
- package/src/corpus/tracker-groups.ts +8 -4
- package/src/corpus/tracker-sort.ts +51 -0
- package/src/corpus/types.ts +24 -1
- package/src/native/app/FoundryApp.tsx +25 -7
- package/src/native/app/__tests__/briefingLink.test.tsx +57 -0
- package/src/native/app/__tests__/briefingServices.test.ts +92 -0
- package/src/native/app/__tests__/launch.test.ts +2 -1
- package/src/native/app/briefingServices.ts +101 -0
- package/src/native/app/config/__tests__/briefingConfig.test.ts +49 -0
- package/src/native/app/config/links.ts +4 -1
- package/src/native/app/config/types.ts +13 -1
- package/src/native/app/config/validate.ts +20 -2
- package/src/native/app/data.ts +3 -3
- package/src/native/app/device.ts +3 -0
- package/src/native/app/launch.ts +4 -0
- package/src/native/app/registry.tsx +3 -1
- package/src/native/app/screens/RecordScreen.tsx +3 -2
- package/src/native/app/services.ts +11 -30
- package/src/native/app/strings.ts +28 -0
- package/src/native/briefing/BriefingCard.tsx +14 -2
- package/src/native/briefing/BriefingReply.tsx +68 -0
- package/src/native/briefing/__tests__/BriefingReply.test.tsx +144 -0
- package/src/native/briefing/__tests__/fakeReply.test.ts +46 -0
- package/src/native/briefing/__tests__/notify.test.ts +42 -1
- package/src/native/briefing/__tests__/replyApi.test.ts +43 -0
- package/src/native/briefing/__tests__/replyController.test.ts +230 -0
- package/src/native/briefing/__tests__/replyPosition.test.ts +116 -0
- package/src/native/briefing/audioPlayer.ts +9 -2
- package/src/native/briefing/controller.ts +50 -5
- package/src/native/briefing/fake.ts +25 -18
- package/src/native/briefing/fakeReply.ts +65 -0
- package/src/native/briefing/index.ts +8 -3
- package/src/native/briefing/notify.ts +42 -0
- package/src/native/briefing/reply.ts +261 -0
- package/src/native/briefing/replyApi.ts +82 -0
- package/src/native/recording/__tests__/deeplink.test.ts +20 -0
- package/src/native/recording/deeplink.ts +7 -0
- package/src/native/tracker/__tests__/itemsChanged.test.ts +13 -0
- package/src/native/tracker/tab.tsx +4 -1
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE BOARD VIEW: what is owed, one column per status (Open, In progress,
|
|
3
|
+
* Blocked). The same rows, filters and sort as the list; only the layout
|
|
4
|
+
* differs. Each card is the shared `CompactItemRow`, so the two views cannot
|
|
5
|
+
* disagree about what a row says.
|
|
6
|
+
*/
|
|
7
|
+
import * as React from 'react';
|
|
8
|
+
|
|
9
|
+
import { compareCommitments } from '../../../corpus/tracker-sort';
|
|
10
|
+
import type { TrackerEntry } from '../../../corpus/tracker-groups';
|
|
11
|
+
import type { CommitmentSort } from '../../../corpus/types';
|
|
12
|
+
|
|
13
|
+
export const BOARD_COLUMNS = [
|
|
14
|
+
{ status: 'open', label: 'Open' },
|
|
15
|
+
{ status: 'in_progress', label: 'In progress' },
|
|
16
|
+
{ status: 'blocked', label: 'Blocked' },
|
|
17
|
+
] as const;
|
|
18
|
+
|
|
19
|
+
export function TrackerBoard({
|
|
20
|
+
entries, sort, renderRow, headingClassName, mutedClassName,
|
|
21
|
+
}: {
|
|
22
|
+
entries: TrackerEntry[];
|
|
23
|
+
sort: CommitmentSort;
|
|
24
|
+
renderRow: (entry: TrackerEntry) => React.ReactNode;
|
|
25
|
+
headingClassName: string;
|
|
26
|
+
mutedClassName: string;
|
|
27
|
+
}) {
|
|
28
|
+
const compare = React.useMemo(() => compareCommitments(sort), [sort]);
|
|
29
|
+
const columns = BOARD_COLUMNS.map((col) => ({
|
|
30
|
+
...col,
|
|
31
|
+
entries: entries.filter((e) => e.item.status === col.status).sort((a, b) => compare(a.item, b.item)),
|
|
32
|
+
}));
|
|
33
|
+
return (
|
|
34
|
+
<div className="grid gap-4 md:grid-cols-3" data-testid="tracker-board">
|
|
35
|
+
{columns.map((col) => (
|
|
36
|
+
<section key={col.status} aria-label={`${col.label} column`} className="min-w-0 space-y-1 rounded-lg bg-gray-50 p-3">
|
|
37
|
+
<h2 className={`flex items-baseline gap-2 ${headingClassName}`}>
|
|
38
|
+
{col.label} <span className="text-sm font-normal text-gray-500">{col.entries.length}</span>
|
|
39
|
+
</h2>
|
|
40
|
+
{col.entries.length ? <ul>{col.entries.map(renderRow)}</ul> : <p className={mutedClassName}>Nothing here.</p>}
|
|
41
|
+
</section>
|
|
42
|
+
))}
|
|
43
|
+
</div>
|
|
44
|
+
);
|
|
45
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sort and view controls for the tracker. Presentational: the page owns both
|
|
3
|
+
* values, and the sort is a SERVER parameter (so it re-reads page one).
|
|
4
|
+
*/
|
|
5
|
+
import * as React from 'react';
|
|
6
|
+
|
|
7
|
+
import { TRACKER_SORTS } from '../../../corpus/tracker-sort';
|
|
8
|
+
import type { CommitmentSort } from '../../../corpus/types';
|
|
9
|
+
|
|
10
|
+
export type TrackerView = 'list' | 'board';
|
|
11
|
+
|
|
12
|
+
const VIEWS: Array<[TrackerView, string]> = [['list', 'List'], ['board', 'Board']];
|
|
13
|
+
|
|
14
|
+
export function TrackerToolbar({
|
|
15
|
+
sort, onSort, view, onView, inputClassName,
|
|
16
|
+
}: {
|
|
17
|
+
sort: CommitmentSort;
|
|
18
|
+
onSort: (sort: CommitmentSort) => void;
|
|
19
|
+
view: TrackerView;
|
|
20
|
+
onView: (view: TrackerView) => void;
|
|
21
|
+
inputClassName: string;
|
|
22
|
+
}) {
|
|
23
|
+
return (
|
|
24
|
+
<div className="flex flex-wrap items-center gap-3">
|
|
25
|
+
<label className="flex items-center gap-2 text-xs text-gray-600">
|
|
26
|
+
Sort
|
|
27
|
+
<select
|
|
28
|
+
className={inputClassName} value={sort} aria-label="Sort to-dos"
|
|
29
|
+
onChange={(e) => onSort(e.target.value as CommitmentSort)}
|
|
30
|
+
>
|
|
31
|
+
{TRACKER_SORTS.map((s) => <option key={s.key} value={s.key}>{s.label}</option>)}
|
|
32
|
+
</select>
|
|
33
|
+
</label>
|
|
34
|
+
<div className="ml-auto flex overflow-hidden rounded-md border border-gray-300" role="group" aria-label="View">
|
|
35
|
+
{VIEWS.map(([key, label]) => (
|
|
36
|
+
<button
|
|
37
|
+
key={key} type="button" aria-pressed={view === key} onClick={() => onView(key)}
|
|
38
|
+
className={`px-3 py-1 text-xs ${view === key ? 'bg-gray-900 text-white' : 'text-gray-700'}`}
|
|
39
|
+
>{label}</button>
|
|
40
|
+
))}
|
|
41
|
+
</div>
|
|
42
|
+
</div>
|
|
43
|
+
);
|
|
44
|
+
}
|
|
@@ -29,6 +29,7 @@ export interface ExecuteInput {
|
|
|
29
29
|
timeZone: string;
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
const reasonOf = (error: unknown) => (error instanceof Error ? error.message : String(error)).slice(0, 200);
|
|
32
33
|
const sameDay = (a: unknown, b: unknown) => (a ? String(a).slice(0, 10) : null) === (b ? String(b).slice(0, 10) : null);
|
|
33
34
|
|
|
34
35
|
/** The fields a patch changes, read off an item, so a reversal can put them back. */
|
|
@@ -93,7 +94,7 @@ async function undoOne(log: ActionLog, input: ExecuteInput, now: number): Promis
|
|
|
93
94
|
return { status: 'applied', spoken: undoText(entry, now, input.timeZone), itemId: entry.itemId };
|
|
94
95
|
} catch (error) {
|
|
95
96
|
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
|
+
return { status: 'failed', spoken: `I could not undo that: ${error instanceof Error ? error.message : 'the change did not go through'}.`, itemId: entry.itemId, reason: reasonOf(error) };
|
|
97
98
|
}
|
|
98
99
|
}
|
|
99
100
|
|
|
@@ -121,7 +122,7 @@ export async function executeVoiceActions(input: ExecuteInput): Promise<ExecuteO
|
|
|
121
122
|
pushUndo(log, { actionId: key, kind: 'create', itemId: created.id, title: action.title, before: {}, after: {}, at: nowIso });
|
|
122
123
|
result = { status: 'applied', spoken: confirmText(action, action.title, now, input.timeZone), itemId: created.id };
|
|
123
124
|
} catch (error) {
|
|
124
|
-
result = { status: 'failed', spoken: `I could not add ${shortTitle(action.title)}.`,
|
|
125
|
+
result = { status: 'failed', spoken: `I could not add ${shortTitle(action.title)}.`, reason: reasonOf(error) };
|
|
125
126
|
}
|
|
126
127
|
} else {
|
|
127
128
|
const patch = patchFor(action, today, nowIso) as ItemPatch;
|
|
@@ -136,8 +137,8 @@ export async function executeVoiceActions(input: ExecuteInput): Promise<ExecuteO
|
|
|
136
137
|
pushUndo(log, { actionId: key, kind: 'edit', itemId: item.id, title: item.title, before, after: patch, at: nowIso });
|
|
137
138
|
result = { status: 'applied', spoken: confirmText(action, item.title, now, input.timeZone), itemId: item.id };
|
|
138
139
|
}
|
|
139
|
-
} catch {
|
|
140
|
-
result = { status: 'failed', spoken: `I could not update ${shortTitle(title)}.`, itemId: action.itemId };
|
|
140
|
+
} catch (error) {
|
|
141
|
+
result = { status: 'failed', spoken: `I could not update ${shortTitle(title)}.`, itemId: action.itemId, reason: reasonOf(error) };
|
|
141
142
|
}
|
|
142
143
|
}
|
|
143
144
|
|
|
@@ -42,7 +42,7 @@ export function createEntityActionLog(http: LogHttp, ownerSub: string): ActionLo
|
|
|
42
42
|
});
|
|
43
43
|
const hit = (page.results ?? []).find((r) => (r.external_id ?? (r as { externalId?: string }).externalId) === externalId && mine(r));
|
|
44
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();
|
|
45
|
+
return stored ? { applied: stored.applied ?? {}, order: stored.order ?? [], stack: stored.stack ?? [], pending: stored.pending ?? [] } : emptyLog();
|
|
46
46
|
},
|
|
47
47
|
async save(log) {
|
|
48
48
|
await http.post('api/v1/entities/upsert', {
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* executor changes. Keep this the ONLY way an action touches an item.
|
|
8
8
|
*/
|
|
9
9
|
import type { Commitment } from '../../types';
|
|
10
|
+
import type { VoiceAction } from '../intent/types';
|
|
10
11
|
|
|
11
12
|
/** What an edit needs to know about an item; a `Commitment` satisfies it. */
|
|
12
13
|
export interface EditableItem {
|
|
@@ -48,6 +49,8 @@ export interface ActionResult {
|
|
|
48
49
|
/** What was said back for this action. */
|
|
49
50
|
spoken: string;
|
|
50
51
|
itemId?: string;
|
|
52
|
+
/** Why a write failed, for logs and the app's diagnostics. Never spoken. */
|
|
53
|
+
reason?: string;
|
|
51
54
|
}
|
|
52
55
|
|
|
53
56
|
/** One undoable change: the fields before and after, to restore and to check nothing moved since. */
|
|
@@ -61,6 +64,22 @@ export interface UndoEntry {
|
|
|
61
64
|
at: string;
|
|
62
65
|
}
|
|
63
66
|
|
|
67
|
+
/** A reply that was understood: kept so applying it, resending it or answering its question needs no second parse. */
|
|
68
|
+
export interface PendingReply {
|
|
69
|
+
/** The client action id of the press that produced it. */
|
|
70
|
+
id: string;
|
|
71
|
+
utterance: string;
|
|
72
|
+
understood: string;
|
|
73
|
+
actions: VoiceAction[];
|
|
74
|
+
source: 'llm' | 'grammar';
|
|
75
|
+
confidence: number;
|
|
76
|
+
/** Set when the reply ended in a question; the next reply may answer it (`inReplyTo`). */
|
|
77
|
+
question?: string;
|
|
78
|
+
/** The spoken confirmation, served to its owner by reference. */
|
|
79
|
+
confirmAudio?: { ref: string; mimeType: string };
|
|
80
|
+
at: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
64
83
|
/** Everything remembered per person: what was applied (idempotency) and what can be undone. */
|
|
65
84
|
export interface ActionLog {
|
|
66
85
|
applied: Record<string, ActionResult>;
|
|
@@ -68,6 +87,8 @@ export interface ActionLog {
|
|
|
68
87
|
order: string[];
|
|
69
88
|
/** Newest last. */
|
|
70
89
|
stack: UndoEntry[];
|
|
90
|
+
/** The latest replies understood, newest last (see `PendingReply`). */
|
|
91
|
+
pending?: PendingReply[];
|
|
71
92
|
}
|
|
72
93
|
|
|
73
94
|
export interface ActionLogStore {
|
|
@@ -58,6 +58,9 @@ export function intentPrompt(ctx: IntentContext): string {
|
|
|
58
58
|
'Other open items (not in the briefing):',
|
|
59
59
|
...(others.length ? others.map((i) => `- ${line(i)}`) : ['(none)']),
|
|
60
60
|
`Undo available: ${ctx.hasUndo ? 'yes' : 'no'}`,
|
|
61
|
+
...(ctx.thread
|
|
62
|
+
? [`Earlier the person said: ${JSON.stringify(ctx.thread.utterance)}`, `You asked: ${JSON.stringify(ctx.thread.question)}`, 'Their next words ANSWER that question; read the two together as one instruction.']
|
|
63
|
+
: []),
|
|
61
64
|
`The person said: ${JSON.stringify(ctx.utterance)}`,
|
|
62
65
|
].join('\n');
|
|
63
66
|
}
|
|
@@ -15,15 +15,23 @@ import type { IntentContext, IntentOptions, IntentResult } from './types';
|
|
|
15
15
|
const DEFAULT_TIMEOUT_MS = 8_000;
|
|
16
16
|
const DEFAULT_MIN_CONFIDENCE = 0.6;
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
/** The plain rules' answer, with the confidence it deserves: sure when it acted, none when it only asked. */
|
|
19
|
+
function byGrammar(ctx: IntentContext, notes: string[]): IntentResult {
|
|
20
|
+
const out = parseWithGrammar(ctx);
|
|
21
|
+
return { ...out, confidence: out.actions.some((a) => a.type !== 'clarify' && a.type !== 'none') ? 1 : 0, notes };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function resolveVoiceIntent(asked: IntentContext, options: IntentOptions = {}): Promise<IntentResult> {
|
|
19
25
|
const notes: string[] = [];
|
|
20
|
-
|
|
26
|
+
// An answer to our question is read WITH what was said first: dates and items come from either.
|
|
27
|
+
const ctx: IntentContext = asked.thread ? { ...asked, utterance: `${asked.thread.utterance} ${asked.utterance}` } : asked;
|
|
28
|
+
if (!asked.utterance.trim()) return byGrammar(ctx, ['empty utterance']);
|
|
21
29
|
|
|
22
30
|
if (options.llm) {
|
|
23
31
|
try {
|
|
24
32
|
const reply = await options.llm.write({
|
|
25
33
|
system: intentSystemPrompt(),
|
|
26
|
-
prompt: intentPrompt(
|
|
34
|
+
prompt: intentPrompt({ ...asked, utterance: asked.utterance }),
|
|
27
35
|
timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
28
36
|
});
|
|
29
37
|
const checked = checkModelReply(reply, ctx);
|
|
@@ -36,14 +44,14 @@ export async function resolveVoiceIntent(ctx: IntentContext, options: IntentOpti
|
|
|
36
44
|
notes.push('model asked; the grammar found a clear match');
|
|
37
45
|
} else if (checked.confidence < (options.minConfidence ?? DEFAULT_MIN_CONFIDENCE)) {
|
|
38
46
|
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}`] };
|
|
47
|
+
return { actions, source: 'llm', confidence: checked.confidence, understood: describeActions(actions, ctx), notes: [`low confidence ${checked.confidence}`] };
|
|
40
48
|
} else {
|
|
41
|
-
return { actions: checked.actions, source: 'llm', understood: describeActions(checked.actions, ctx), notes };
|
|
49
|
+
return { actions: checked.actions, source: 'llm', confidence: checked.confidence, understood: describeActions(checked.actions, ctx), notes };
|
|
42
50
|
}
|
|
43
51
|
}
|
|
44
52
|
} catch (error) {
|
|
45
53
|
notes.push(`model failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
46
54
|
}
|
|
47
55
|
}
|
|
48
|
-
return
|
|
56
|
+
return byGrammar(ctx, notes);
|
|
49
57
|
}
|
|
@@ -26,6 +26,11 @@ export interface IntentContext {
|
|
|
26
26
|
readingId: string | null;
|
|
27
27
|
/** Whether the undo stack has anything on it. */
|
|
28
28
|
hasUndo: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Set when `utterance` ANSWERS a question this reply asked: what was said first and what was asked. The model sees
|
|
31
|
+
* both; the grammar and the grounding check read the two utterances as one ("move that one to Friday" + "the bench one").
|
|
32
|
+
*/
|
|
33
|
+
thread?: { utterance: string; question: string };
|
|
29
34
|
}
|
|
30
35
|
|
|
31
36
|
export type VoiceAction =
|
|
@@ -45,6 +50,8 @@ export type VoiceAction =
|
|
|
45
50
|
export interface IntentResult {
|
|
46
51
|
actions: VoiceAction[];
|
|
47
52
|
source: 'llm' | 'grammar';
|
|
53
|
+
/** 0..1: the model's own figure, or 1 when the plain rules acted on a named item, 0 when they only asked. */
|
|
54
|
+
confidence?: number;
|
|
48
55
|
/** One line to show before applying: "Move Pick up printer paper to Friday". */
|
|
49
56
|
understood: string;
|
|
50
57
|
/** Why the model's answer was not used, for logs and the accuracy probe. */
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* handleBriefingReply: a spoken reply -> understood -> (previewed or applied) -> spoken back.
|
|
3
|
+
*
|
|
4
|
+
* find the caller's briefing -> [replay? answer from the log] -> words (transcribe if audio)
|
|
5
|
+
* -> intent (model, then plain rules) -> keep it as PENDING -> apply now (sure) or wait for `apply`
|
|
6
|
+
* -> executor (idempotent, undoable, through the item edit seam) -> speak the result.
|
|
7
|
+
*
|
|
8
|
+
* Request-free so a Next route, a worker and a test all call the same thing.
|
|
9
|
+
*/
|
|
10
|
+
import { executeVoiceActions, speakConfirmation, type SpokenConfirmation } from '../actions';
|
|
11
|
+
import type { ActionLog, ActionResult, PendingReply } from '../actions/types';
|
|
12
|
+
import { readingAt, resolveVoiceIntent } from '../intent';
|
|
13
|
+
import type { IntentContext, IntentItem, IntentResult, VoiceAction } from '../intent';
|
|
14
|
+
import { createEntityBriefingStore, type BriefingRecord } from '../store';
|
|
15
|
+
import { ReplyError, type BriefingReplyDeps, type ReplyConfirmation, type ReplyRequest, type ReplyResult } from './types';
|
|
16
|
+
|
|
17
|
+
export const CLIENT_ACTION_ID = /^[A-Za-z0-9_-]{8,64}$/;
|
|
18
|
+
const PENDING_KEPT = 12;
|
|
19
|
+
const DEFAULT_MIN_AUTO = 0.85;
|
|
20
|
+
/** Open items offered to the transcriber as vocabulary, beyond the ones just read. */
|
|
21
|
+
const MAX_HINTS = 20;
|
|
22
|
+
export const MAX_REPLY_AUDIO_BYTES = 10 * 1024 * 1024;
|
|
23
|
+
|
|
24
|
+
export const replyAudioPath = (briefingId: string, clientActionId: string) =>
|
|
25
|
+
`/corpus/briefing/${encodeURIComponent(briefingId)}/reply/${encodeURIComponent(clientActionId)}/audio`;
|
|
26
|
+
|
|
27
|
+
const asksOnly = (actions: VoiceAction[]) => actions.every((a) => a.type === 'clarify' || a.type === 'none');
|
|
28
|
+
const intentItem = (i: { id: string; title: string; group?: string; focusName?: string; linearIdentifier?: string }): IntentItem => ({
|
|
29
|
+
id: i.id, title: i.title, ...(i.focusName ?? i.group ? { focusName: i.focusName ?? i.group } : {}),
|
|
30
|
+
...(i.linearIdentifier ? { linearIdentifier: i.linearIdentifier } : {}),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
function validate(req: ReplyRequest) {
|
|
34
|
+
if (req.subject?.kind === 'question') throw new ReplyError('Answering a question by voice is not available here yet.', 501);
|
|
35
|
+
if (req.subject?.kind !== 'briefing' || !req.subject.id) throw new ReplyError('Say which briefing this is a reply to.', 400);
|
|
36
|
+
if (!CLIENT_ACTION_ID.test(req.clientActionId ?? '')) throw new ReplyError('Send a clientActionId (8-64 letters, digits, - or _), fresh for each press.', 400);
|
|
37
|
+
if (!req.undo && !req.apply && req.utterance === undefined && !req.audio) throw new ReplyError('Send what was said: audio or an utterance.', 400);
|
|
38
|
+
if (req.audio && req.audio.audio.byteLength > MAX_REPLY_AUDIO_BYTES) throw new ReplyError('That recording is too long for a reply.', 413);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The results already recorded under this press, in order. */
|
|
42
|
+
function recorded(log: ActionLog, id: string): ActionResult[] {
|
|
43
|
+
const out: ActionResult[] = [];
|
|
44
|
+
for (let n = 0; log.applied[`${id}#${n}`]; n += 1) out.push(log.applied[`${id}#${n}`]);
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function update(deps: BriefingReplyDeps, change: (log: ActionLog) => void) {
|
|
49
|
+
const log = await deps.log.load();
|
|
50
|
+
change(log);
|
|
51
|
+
await deps.log.save(log);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function speak(deps: BriefingReplyDeps, text: string, briefingId: string, id: string): Promise<{ confirmation: ReplyConfirmation; audio?: PendingReply['confirmAudio'] }> {
|
|
55
|
+
let ref = '';
|
|
56
|
+
const spoken: SpokenConfirmation = await speakConfirmation({
|
|
57
|
+
text,
|
|
58
|
+
clientActionId: id,
|
|
59
|
+
synthesize: deps.synthesize,
|
|
60
|
+
audio: deps.audio ? { put: deps.audio.put, url: async (r) => { ref = r; return replyAudioPath(briefingId, id); } } : undefined,
|
|
61
|
+
});
|
|
62
|
+
const confirmation: ReplyConfirmation = { text: spoken.text, audioUrl: spoken.audioUrl, ...(spoken.mimeType ? { mimeType: spoken.mimeType } : {}), ...(spoken.reason ? { reason: spoken.reason } : {}) };
|
|
63
|
+
return { confirmation, ...(spoken.audioUrl && ref ? { audio: { ref, mimeType: spoken.mimeType ?? 'audio/mpeg' } } : {}) };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function handleBriefingReply(deps: BriefingReplyDeps, req: ReplyRequest): Promise<ReplyResult> {
|
|
67
|
+
validate(req);
|
|
68
|
+
const now = (deps.now ?? Date.now)();
|
|
69
|
+
const id = req.clientActionId;
|
|
70
|
+
const briefingId = req.subject.id;
|
|
71
|
+
const store = deps.store ?? createEntityBriefingStore(deps.http, deps.ownerSub);
|
|
72
|
+
const record: BriefingRecord | null = await store.get(briefingId);
|
|
73
|
+
if (!record) throw new ReplyError('Not found.', 404);
|
|
74
|
+
const timeZone = req.timeZone || record.context.timeZone || deps.timeZone || 'UTC';
|
|
75
|
+
const log = await deps.log.load();
|
|
76
|
+
const mine = (log.pending ?? []).find((p) => p.id === id);
|
|
77
|
+
|
|
78
|
+
const base = {
|
|
79
|
+
clientActionId: id,
|
|
80
|
+
results: [] as ActionResult[],
|
|
81
|
+
question: null as string | null,
|
|
82
|
+
confirmation: null as ReplyConfirmation | null,
|
|
83
|
+
refresh: false,
|
|
84
|
+
replayed: false,
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
// 1. Already handled: answer from the log. Nothing is transcribed, parsed or written again.
|
|
88
|
+
const done = recorded(log, id);
|
|
89
|
+
if (done.length) {
|
|
90
|
+
const text = done.map((r) => r.spoken).join(' ');
|
|
91
|
+
const asked = mine ? asksOnly(mine.actions) : false;
|
|
92
|
+
return {
|
|
93
|
+
...base,
|
|
94
|
+
kind: asked ? 'clarify' : 'applied',
|
|
95
|
+
utterance: mine?.utterance ?? '', understood: mine?.understood ?? '', actions: mine?.actions ?? [],
|
|
96
|
+
source: mine?.source ?? 'grammar', confidence: mine?.confidence ?? 1, needsConfirm: false,
|
|
97
|
+
results: done, question: asked ? (mine?.question ?? text) : null,
|
|
98
|
+
confirmation: { text, audioUrl: mine?.confirmAudio ? replyAudioPath(briefingId, id) : null, ...(mine?.confirmAudio ? { mimeType: mine.confirmAudio.mimeType } : {}) },
|
|
99
|
+
undoDepth: log.stack.length, refresh: false, replayed: true,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// 2. Undo: no words, straight to the executor.
|
|
104
|
+
let entry: PendingReply | undefined = mine;
|
|
105
|
+
if (req.undo) {
|
|
106
|
+
entry = { id, utterance: 'undo', understood: 'Undo the last change', actions: [{ type: 'undo' }], source: 'grammar', confidence: 1, at: new Date(now).toISOString() };
|
|
107
|
+
} else if (req.apply && !entry) {
|
|
108
|
+
throw new ReplyError('That reply is no longer waiting. Say it again.', 409, 'expired');
|
|
109
|
+
} else if (!entry) {
|
|
110
|
+
entry = await understand(deps, req, record, log, timeZone, now);
|
|
111
|
+
const kept = entry;
|
|
112
|
+
await update(deps, (l) => { l.pending = [...(l.pending ?? []).filter((p) => p.id !== kept.id), kept].slice(-PENDING_KEPT); });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// 3. Wait for a yes, or go.
|
|
116
|
+
const mode = req.mode ?? 'auto';
|
|
117
|
+
const sure = entry.confidence >= (deps.minAutoConfidence ?? DEFAULT_MIN_AUTO) && !entry.actions.some((a) => a.type === 'clarify' || a.type === 'none');
|
|
118
|
+
const go = req.undo || req.apply || asksOnly(entry.actions) || (mode === 'auto' && sure);
|
|
119
|
+
const view = { utterance: entry.utterance, understood: entry.understood, actions: entry.actions, source: entry.source, confidence: entry.confidence };
|
|
120
|
+
if (!go) {
|
|
121
|
+
return { ...base, ...view, kind: 'preview', needsConfirm: true, undoDepth: log.stack.length };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// 4. Apply and say it back.
|
|
125
|
+
const outcome = await executeVoiceActions({
|
|
126
|
+
actions: entry.actions, clientActionId: id, seam: deps.seam, log: deps.log, ownerSub: deps.ownerSub, now: () => now, timeZone,
|
|
127
|
+
});
|
|
128
|
+
const asked = asksOnly(entry.actions);
|
|
129
|
+
const question = asked ? outcome.results.map((r) => r.spoken).join(' ') : null;
|
|
130
|
+
const said = await speak(deps, outcome.text, briefingId, id);
|
|
131
|
+
const finalEntry = entry;
|
|
132
|
+
await update(deps, (l) => {
|
|
133
|
+
const rest = (l.pending ?? []).filter((p) => p.id !== finalEntry.id);
|
|
134
|
+
l.pending = [...rest, { ...finalEntry, ...(question ? { question } : {}), ...(said.audio ? { confirmAudio: said.audio } : {}) }].slice(-PENDING_KEPT);
|
|
135
|
+
});
|
|
136
|
+
return {
|
|
137
|
+
...base, ...view,
|
|
138
|
+
kind: asked ? 'clarify' : 'applied', needsConfirm: false, results: outcome.results, question,
|
|
139
|
+
confirmation: said.confirmation, undoDepth: outcome.undoDepth, refresh: outcome.applied > 0, replayed: outcome.replayed,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Words -> actions, grounded in what was just read. */
|
|
144
|
+
async function understand(deps: BriefingReplyDeps, req: ReplyRequest, record: BriefingRecord, log: ActionLog, timeZone: string, now: number): Promise<PendingReply> {
|
|
145
|
+
const briefed = record.items.map(intentItem);
|
|
146
|
+
const briefedIds = new Set(briefed.map((i) => i.id));
|
|
147
|
+
// "That other thing" names an open item that was not read out: it is as likely to be misheard as a spoken one.
|
|
148
|
+
const open = (await deps.loadItems().catch(() => [])).filter((i) => !briefedIds.has(i.id)).map(intentItem);
|
|
149
|
+
let utterance = req.utterance ?? '';
|
|
150
|
+
if (req.audio) {
|
|
151
|
+
if (!deps.transcribe) throw new ReplyError('Speech to text is not set up.', 503, 'transcription_unavailable');
|
|
152
|
+
try {
|
|
153
|
+
utterance = await deps.transcribe({ audio: req.audio.audio, mimeType: req.audio.mimeType, hints: [...briefed, ...open.slice(0, MAX_HINTS)].map((i) => i.title) });
|
|
154
|
+
} catch (error) {
|
|
155
|
+
throw new ReplyError(`I could not make out the recording: ${error instanceof Error ? error.message : 'transcription failed'}`, 502, 'transcription_failed');
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
utterance = utterance.trim();
|
|
159
|
+
const at = new Date(now).toISOString();
|
|
160
|
+
if (!utterance) {
|
|
161
|
+
const actions: VoiceAction[] = [{ type: 'clarify', question: 'Sorry, I did not catch that. Can you say that again?' }];
|
|
162
|
+
return { id: req.clientActionId, utterance, understood: actions[0].type === 'clarify' ? actions[0].question : '', actions, source: 'grammar', confidence: 0, at };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const earlier = req.inReplyTo ? (log.pending ?? []).find((p) => p.id === req.inReplyTo && p.question) : undefined;
|
|
166
|
+
const ctx: IntentContext = {
|
|
167
|
+
utterance, now, timeZone, briefed, open,
|
|
168
|
+
readingId: req.position ? readingAt(record.context, { ...req.position, textLength: record.text.length }) : null,
|
|
169
|
+
hasUndo: log.stack.length > 0,
|
|
170
|
+
...(earlier ? { thread: { utterance: earlier.utterance, question: earlier.question as string } } : {}),
|
|
171
|
+
};
|
|
172
|
+
const intent: IntentResult = await resolveVoiceIntent(ctx, { llm: deps.intentLlm ?? null, ...(deps.intentTimeoutMs ? { timeoutMs: deps.intentTimeoutMs } : {}) });
|
|
173
|
+
return { id: req.clientActionId, utterance, understood: intent.understood, actions: intent.actions, source: intent.source, confidence: intent.confidence ?? (asksOnly(intent.actions) ? 0 : 1), at };
|
|
174
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { handleBriefingReply, replyAudioPath, CLIENT_ACTION_ID } from './handle';
|
|
2
|
+
export { briefingReplyResponse, briefingReplyAudioResponse } from './respond';
|
|
3
|
+
export { ReplyError } from './types';
|
|
4
|
+
export type {
|
|
5
|
+
BriefingReplyDeps, ReplyConfirmation, ReplyRequest, ReplyResult, ReplySubject,
|
|
6
|
+
} from './types';
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fetch-`Response` wrappers for the tenant frontend's route files:
|
|
3
|
+
* POST /corpus/briefing/reply JSON {briefingId, clientActionId, utterance?, ...} or multipart with `audio`
|
|
4
|
+
* GET /corpus/briefing/<id>/reply/<clientActionId>/audio the spoken confirmation, to its owner only
|
|
5
|
+
*/
|
|
6
|
+
import { voiceErrorResponse } from '../../voice-manage';
|
|
7
|
+
import { isTimeZone } from '../../spoken-time';
|
|
8
|
+
import { emptyLog } from '../actions/log';
|
|
9
|
+
import { createEntityBriefingStore } from '../store';
|
|
10
|
+
import { CLIENT_ACTION_ID, MAX_REPLY_AUDIO_BYTES, handleBriefingReply } from './handle';
|
|
11
|
+
import { ReplyError, type BriefingReplyDeps, type ReplyRequest } from './types';
|
|
12
|
+
|
|
13
|
+
const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined);
|
|
14
|
+
const bool = (v: unknown) => v === true || v === 'true' || v === '1';
|
|
15
|
+
|
|
16
|
+
function position(raw: unknown): ReplyRequest['position'] {
|
|
17
|
+
let value = raw;
|
|
18
|
+
if (typeof raw === 'string') { try { value = JSON.parse(raw); } catch { return undefined; } }
|
|
19
|
+
if (!value || typeof value !== 'object') return undefined;
|
|
20
|
+
const out: NonNullable<ReplyRequest['position']> = {};
|
|
21
|
+
for (const key of ['charPosition', 'seconds', 'durationSeconds'] as const) {
|
|
22
|
+
const n = Number((value as Record<string, unknown>)[key]);
|
|
23
|
+
if (Number.isFinite(n) && n >= 0) out[key] = n;
|
|
24
|
+
}
|
|
25
|
+
return Object.keys(out).length ? out : undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function parse(request: Request): Promise<ReplyRequest> {
|
|
29
|
+
const type = request.headers.get('content-type') ?? '';
|
|
30
|
+
let fields: Record<string, unknown>;
|
|
31
|
+
let audio: ReplyRequest['audio'];
|
|
32
|
+
if (type.includes('multipart/form-data')) {
|
|
33
|
+
// Typed by what is used: the native build has no DOM lib, so `FormData`'s methods are not declared there.
|
|
34
|
+
const form = (await request.formData().catch(() => { throw new ReplyError('Send the reply as multipart form data or JSON.', 400); })) as unknown as {
|
|
35
|
+
entries(): Iterable<[string, unknown]>;
|
|
36
|
+
get(name: string): unknown;
|
|
37
|
+
};
|
|
38
|
+
fields = Object.fromEntries([...form.entries()].filter(([, v]) => typeof v === 'string'));
|
|
39
|
+
const file = form.get('audio');
|
|
40
|
+
if (file instanceof Blob && file.size > 0) {
|
|
41
|
+
if (file.size > MAX_REPLY_AUDIO_BYTES) throw new ReplyError('That recording is too long for a reply.', 413);
|
|
42
|
+
audio = { audio: new Uint8Array(await file.arrayBuffer()), mimeType: file.type || 'audio/mp4' };
|
|
43
|
+
}
|
|
44
|
+
} else {
|
|
45
|
+
try { fields = JSON.parse((await request.text()) || '{}'); } catch { throw new ReplyError('Send JSON, or multipart with the recording.', 400); }
|
|
46
|
+
if (!fields || typeof fields !== 'object') throw new ReplyError('Send JSON, or multipart with the recording.', 400);
|
|
47
|
+
}
|
|
48
|
+
const zone = str(fields.timeZone);
|
|
49
|
+
return {
|
|
50
|
+
subject: (fields.subject as ReplyRequest['subject'] | undefined) ?? { kind: 'briefing', id: str(fields.briefingId) ?? '' },
|
|
51
|
+
clientActionId: str(fields.clientActionId) ?? '',
|
|
52
|
+
...(typeof fields.utterance === 'string' ? { utterance: fields.utterance } : {}),
|
|
53
|
+
...(audio ? { audio } : {}),
|
|
54
|
+
...(position(fields.position) ? { position: position(fields.position) } : {}),
|
|
55
|
+
...(zone && isTimeZone(zone) ? { timeZone: zone } : {}),
|
|
56
|
+
...(fields.mode === 'preview' ? { mode: 'preview' as const } : {}),
|
|
57
|
+
...(bool(fields.apply) ? { apply: true } : {}),
|
|
58
|
+
...(bool(fields.undo) ? { undo: true } : {}),
|
|
59
|
+
...(str(fields.inReplyTo) ? { inReplyTo: str(fields.inReplyTo) } : {}),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const failure = (error: unknown) => {
|
|
64
|
+
if (error instanceof ReplyError) return Response.json({ detail: error.message, ...(error.code ? { code: error.code } : {}) }, { status: error.status });
|
|
65
|
+
return voiceErrorResponse(error);
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export async function briefingReplyResponse(request: Request, deps: BriefingReplyDeps): Promise<Response> {
|
|
69
|
+
try {
|
|
70
|
+
return Response.json(await handleBriefingReply(deps, await parse(request)));
|
|
71
|
+
} catch (error) {
|
|
72
|
+
return failure(error);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The spoken confirmation of one reply. The log and the briefing are read as the caller, so anyone else's id is a 404. */
|
|
77
|
+
export async function briefingReplyAudioResponse(
|
|
78
|
+
briefingId: string,
|
|
79
|
+
clientActionId: string,
|
|
80
|
+
deps: Pick<BriefingReplyDeps, 'http' | 'ownerSub' | 'log' | 'store'> & { audio: { get(ref: string): Promise<{ audio: Uint8Array; mimeType: string }> } },
|
|
81
|
+
): Promise<Response> {
|
|
82
|
+
const notFound = () => Response.json({ detail: 'Not found.' }, { status: 404 });
|
|
83
|
+
if (!CLIENT_ACTION_ID.test(clientActionId)) return notFound();
|
|
84
|
+
try {
|
|
85
|
+
const store = deps.store ?? createEntityBriefingStore(deps.http, deps.ownerSub);
|
|
86
|
+
if (!(await store.get(briefingId))) return notFound();
|
|
87
|
+
const log = await deps.log.load().catch(() => emptyLog());
|
|
88
|
+
const ref = (log.pending ?? []).find((p) => p.id === clientActionId)?.confirmAudio;
|
|
89
|
+
if (!ref) return notFound();
|
|
90
|
+
const { audio, mimeType } = await deps.audio.get(ref.ref);
|
|
91
|
+
return new Response(audio as BodyInit, { headers: { 'content-type': mimeType, 'cache-control': 'private, max-age=300', 'content-length': String(audio.byteLength) } });
|
|
92
|
+
} catch (error) {
|
|
93
|
+
return failure(error);
|
|
94
|
+
}
|
|
95
|
+
}
|