@startsimpli/integrations 0.2.150 → 0.2.151

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.
@@ -12,3 +12,12 @@ export type {
12
12
  AssumedValue, DerivedQuestion, ItemView, OpenQuestion, QuestionAnswer, QuestionCandidate,
13
13
  QuestionKind, QuestionResolution, QuestionStatus,
14
14
  } from './types';
15
+ export { answerQuestionByVoice, validateAnswerRequest, VoiceAnswerError } from './voice';
16
+ export type { VoiceAnswerDeps, VoiceAnswerRequest, VoiceAnswerResult } from './voice';
17
+ export { parseSpokenAnswer, offeredOptions } from './voice-parse';
18
+ export type { AnswerContext, AnswerOption, SpokenAnswer } from './voice-parse';
19
+ export { questionAnswerResponse, questionAnswerAudioResponse } from './respond';
20
+ export { composeCheckIn } from './checkin';
21
+ export type { CheckIn, CheckInEntry, CheckInOptions } from './checkin';
22
+ export { buildCheckIn } from './checkin-handle';
23
+ export type { CheckInResult } from './checkin-handle';
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Fetch-`Response` wrappers for the tenant frontend's route files (bd startsim-tmrvi.5):
3
+ * POST /corpus/questions/answer JSON {clientActionId, utterance?, questionId?} or multipart with `audio`
4
+ * GET /corpus/questions/audio/<id> the spoken reply to one press, to its owner only
5
+ */
6
+ import { voiceErrorResponse } from '../voice-manage';
7
+ import { isTimeZone } from '../spoken-time';
8
+ import { emptyLog } from '../briefing/actions/log';
9
+ import type { ActionLogStore } from '../briefing/actions/types';
10
+ import {
11
+ CLIENT_ACTION_ID, MAX_ANSWER_AUDIO_BYTES, VoiceAnswerError, answerQuestionByVoice,
12
+ type VoiceAnswerDeps, type VoiceAnswerRequest,
13
+ } from './voice';
14
+
15
+ const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined);
16
+
17
+ async function parse(request: Request): Promise<VoiceAnswerRequest> {
18
+ const type = request.headers.get('content-type') ?? '';
19
+ let fields: Record<string, unknown>;
20
+ let audio: VoiceAnswerRequest['audio'];
21
+ if (type.includes('multipart/form-data')) {
22
+ // Typed by what is used: the native build has no DOM lib, so `FormData`'s methods are not declared there.
23
+ const form = (await request.formData().catch(() => { throw new VoiceAnswerError('Send the answer as multipart form data or JSON.', 400); })) as unknown as {
24
+ entries(): Iterable<[string, unknown]>;
25
+ get(name: string): unknown;
26
+ };
27
+ fields = Object.fromEntries([...form.entries()].filter(([, v]) => typeof v === 'string'));
28
+ const file = form.get('audio');
29
+ if (file instanceof Blob && file.size > 0) {
30
+ if (file.size > MAX_ANSWER_AUDIO_BYTES) throw new VoiceAnswerError('That recording is too long for an answer.', 413);
31
+ audio = { audio: new Uint8Array(await file.arrayBuffer()), mimeType: file.type || 'audio/mp4' };
32
+ }
33
+ } else {
34
+ try { fields = JSON.parse((await request.text()) || '{}'); } catch { throw new VoiceAnswerError('Send JSON, or multipart with the recording.', 400); }
35
+ if (!fields || typeof fields !== 'object') throw new VoiceAnswerError('Send JSON, or multipart with the recording.', 400);
36
+ }
37
+ const zone = str(fields.timeZone);
38
+ return {
39
+ clientActionId: str(fields.clientActionId) ?? '',
40
+ ...(str(fields.questionId) ? { questionId: str(fields.questionId) } : {}),
41
+ ...(typeof fields.utterance === 'string' ? { utterance: fields.utterance } : {}),
42
+ ...(audio ? { audio } : {}),
43
+ ...(zone && isTimeZone(zone) ? { timeZone: zone } : {}),
44
+ };
45
+ }
46
+
47
+ const failure = (error: unknown) => {
48
+ if (error instanceof VoiceAnswerError) return Response.json({ detail: error.message, ...(error.code ? { code: error.code } : {}) }, { status: error.status });
49
+ return voiceErrorResponse(error);
50
+ };
51
+
52
+ export async function questionAnswerResponse(request: Request, deps: VoiceAnswerDeps): Promise<Response> {
53
+ try {
54
+ return Response.json(await answerQuestionByVoice(deps, await parse(request)));
55
+ } catch (error) {
56
+ return failure(error);
57
+ }
58
+ }
59
+
60
+ /** The spoken reply to one press. The log is the caller's own, so anyone else's id is a 404. */
61
+ export async function questionAnswerAudioResponse(
62
+ clientActionId: string,
63
+ deps: { log: ActionLogStore; audio: { get(ref: string): Promise<{ audio: Uint8Array; mimeType: string }> } },
64
+ ): Promise<Response> {
65
+ const notFound = () => Response.json({ detail: 'Not found.' }, { status: 404 });
66
+ if (!CLIENT_ACTION_ID.test(clientActionId)) return notFound();
67
+ try {
68
+ const log = await deps.log.load().catch(() => emptyLog());
69
+ const ref = (log.pending ?? []).find((p) => p.id === clientActionId)?.confirmAudio;
70
+ if (!ref) return notFound();
71
+ const { audio, mimeType } = await deps.audio.get(ref.ref);
72
+ return new Response(audio as BodyInit, { headers: { 'content-type': mimeType, 'cache-control': 'private, max-age=300', 'content-length': String(audio.byteLength) } });
73
+ } catch (error) {
74
+ return failure(error);
75
+ }
76
+ }
@@ -3,7 +3,7 @@ import type { CorpusHttp } from '../client';
3
3
  import type { TenantEntity } from '../entities';
4
4
  import {
5
5
  OPEN_QUESTION_TYPE,
6
- type AssumedValue, type OpenQuestion, type QuestionCandidate, type QuestionKind,
6
+ type AssumedValue, type OpenQuestion, type QuestionAnswer, type QuestionCandidate, type QuestionKind,
7
7
  type QuestionResolution, type QuestionStatus,
8
8
  } from './types';
9
9
 
@@ -34,6 +34,8 @@ export function toQuestion(entity: TenantEntity): OpenQuestion {
34
34
  const resolvedAt = str(pick(d, 'resolved_at', 'resolvedAt'));
35
35
  const resolution = str(d.resolution);
36
36
  const noteId = str(pick(d, 'note_id', 'noteId'));
37
+ const answer = json<QuestionAnswer | null>(d.answer, null);
38
+ const snoozedUntil = str(pick(d, 'snoozed_until', 'snoozedUntil'));
37
39
  return {
38
40
  id: String(entity.id),
39
41
  itemId: str(pick(d, 'item_id', 'itemId')),
@@ -46,6 +48,8 @@ export function toQuestion(entity: TenantEntity): OpenQuestion {
46
48
  ownerSub: str(pick(d, 'owner_sub', 'ownerSub')),
47
49
  ...(noteId ? { noteId } : {}),
48
50
  ...(resolution ? { resolution: resolution as QuestionResolution } : {}),
51
+ ...(answer && typeof answer === 'object' ? { answer } : {}),
52
+ ...(snoozedUntil ? { snoozedUntil } : {}),
49
53
  createdAt: str(pick(d, 'created_at', 'createdAt')),
50
54
  updatedAt: str(pick(d, 'updated_at', 'updatedAt')),
51
55
  ...(resolvedAt ? { resolvedAt } : {}),
@@ -55,6 +55,7 @@ export async function syncOpenQuestions(deps: QuestionDeps): Promise<{ opened: n
55
55
  opened += 1;
56
56
  } else if (have.status !== 'open') {
57
57
  if (!d.reopens) continue;
58
+ if (have.snoozedUntil && have.snoozedUntil > iso()) continue; // skipped for now
58
59
  await store.put(d.itemId, d.kind, d.question, { ...body, status: 'open', resolution: '', resolved_at: '', created_at: iso(), updated_at: iso() });
59
60
  opened += 1;
60
61
  } else if (have.question !== d.question || have.score !== score) {
@@ -13,7 +13,7 @@ export type QuestionKind = (typeof QUESTION_KINDS)[number];
13
13
  export type QuestionStatus = 'open' | 'resolved' | 'expired';
14
14
 
15
15
  /** Why a question left the queue. */
16
- export type QuestionResolution = 'answered' | 'item_changed' | 'item_closed' | 'item_gone';
16
+ export type QuestionResolution = 'answered' | 'skipped' | 'item_changed' | 'item_closed' | 'item_gone';
17
17
 
18
18
  export interface AssumedValue {
19
19
  value: string | null;
@@ -43,6 +43,10 @@ export interface OpenQuestion {
43
43
  ownerSub: string;
44
44
  noteId?: string;
45
45
  resolution?: QuestionResolution;
46
+ /** What it was answered with, once resolved by an answer. */
47
+ answer?: QuestionAnswer;
48
+ /** A skipped question is not asked again before this instant (ISO). */
49
+ snoozedUntil?: string;
46
50
  createdAt: string;
47
51
  updatedAt: string;
48
52
  resolvedAt?: string;
@@ -53,6 +57,10 @@ export interface QuestionAnswer {
53
57
  value: string;
54
58
  /** Human label for the value (an owner's name). */
55
59
  label?: string;
60
+ /** Set when the answer was spoken: the press that gave it, so a repeat press does nothing twice. */
61
+ via?: string;
62
+ /** What the item held before, so a spoken "undo" can put it back. */
63
+ prior?: { dueAt?: string | null };
56
64
  }
57
65
 
58
66
  /** What the queue needs to know about an item (from its commitment row). */
@@ -88,5 +96,5 @@ export const OPEN_QUESTION_ATTRIBUTES: Array<[string, string]> = [
88
96
  ['item_id', 'text'], ['kind', 'text'], ['question', 'text'], ['status', 'text'],
89
97
  ['assumed', 'text'], ['candidates', 'text'], ['answer', 'text'], ['score', 'integer'],
90
98
  ['owner_sub', 'text'], ['note_id', 'text'], ['resolution', 'text'],
91
- ['created_at', 'date'], ['updated_at', 'date'], ['resolved_at', 'date'],
99
+ ['created_at', 'date'], ['updated_at', 'date'], ['resolved_at', 'date'], ['snoozed_until', 'date'],
92
100
  ];
@@ -0,0 +1,98 @@
1
+ /**
2
+ * WHAT A SPOKEN ANSWER TO A CLARIFYING QUESTION MEANS (bd startsim-tmrvi.5).
3
+ *
4
+ * Its own small grammar, NOT the briefing reply grammar: there "skip" drops a
5
+ * to-do and "today" pulls one in, here "skip" leaves the question for later and
6
+ * "today" is the answer. A reply this cannot place becomes a short question back,
7
+ * never a guess and never an edit. Pure: no model, no storage.
8
+ */
9
+ import { normalizeSpeech, parseWhen, splitWhen } from '../briefing/intent/dates';
10
+ import { contentWords, matchItems } from '../briefing/intent/match';
11
+ import { speakable } from '../briefing/speak';
12
+ import type { OpenQuestion } from './types';
13
+
14
+ export interface AnswerOption { value: string; label: string }
15
+
16
+ export interface AnswerContext {
17
+ now: number;
18
+ timeZone: string;
19
+ /** The choices a project / team / owner answer may name, by label. */
20
+ options: AnswerOption[];
21
+ }
22
+
23
+ export type SpokenAnswer =
24
+ /** `value` is a date (or '' to clear it), or an option's value. `spoken` is how it is said back. */
25
+ | { kind: 'answer'; value: string; label?: string; spoken: string }
26
+ /** "Yes, keep it": take the guess as the answer. */
27
+ | { kind: 'accept' }
28
+ /** "Not now": leave it for later. */
29
+ | { kind: 'skip' }
30
+ | { kind: 'undo' }
31
+ | { kind: 'unclear'; question: string };
32
+
33
+ const UNDO = /^(?:undo|undo (?:that|it|the last(?: one| answer)?)|never ?mind|take (?:that|it) back|go back|scratch that|oops)$/;
34
+ const SKIP = /^(?:skip(?: it| this| that| this one| that one)?|not now|ask me (?:later|again|tomorrow)|pass|leave it|come back (?:to (?:it|this|that) )?later|maybe later|i (?:don't|do not) know(?: yet)?|no idea)$/;
35
+ const YES = /^(?:(?:yes|yeah|yep|yup|sure|ok|okay)[,\s]+)?(?:yes|yeah|yep|yup|sure|correct|right|exactly|ok|okay|alright|that(?:'s| is) (?:right|correct|fine|good|it)|sounds (?:good|right)|looks (?:good|right)|keep (?:it|that|them)|go with (?:that|it)|that works|fine|good|do that)(?: please| thanks| thank you)?$/;
36
+ const LEAD = /^(?:(?:hey|um|uh|so|well|actually|please|oh|hmm|just|and|then)\b[,\s]*)+/;
37
+
38
+ const ORDINALS: Array<[RegExp, number]> = [
39
+ [/\b(?:first|1st|number one|option one)\b/, 0], [/\b(?:second|2nd|number two|option two)\b/, 1],
40
+ [/\b(?:third|3rd|number three|option three)\b/, 2], [/\b(?:fourth|4th|number four)\b/, 3],
41
+ ];
42
+
43
+ /** Words that frame a choice without naming it: "that's the marketing project". */
44
+ const CHOICE_FILLER = /\b(?:thats|that's|that is|its|it's|it is|project|team|space|folder|owner|goes|belongs|go|put|file|filed|under|in|into|for|to|with|assign|assigned|give|make)\b/g;
45
+
46
+ const unclear = (question: string): SpokenAnswer => ({ kind: 'unclear', question });
47
+ const orList = (labels: string[]) => (labels.length < 2 ? labels.join('') : `${labels.slice(0, -1).join(', ')} or ${labels[labels.length - 1]}`);
48
+
49
+ /** The options this question offered, best first, as the labels the person heard. */
50
+ export function offeredOptions(q: OpenQuestion, options: AnswerOption[]): AnswerOption[] {
51
+ const byValue = new Map(options.map((o) => [o.value, o]));
52
+ const offered = q.candidates.map((c) => byValue.get(c.value)).filter((o): o is AnswerOption => Boolean(o));
53
+ return offered.length ? offered : options.slice(0, 4);
54
+ }
55
+
56
+ function parseDate(q: OpenQuestion, text: string, ctx: AnswerContext): SpokenAnswer {
57
+ const whole = parseWhen(text, ctx.now, ctx.timeZone);
58
+ const part = whole ? null : splitWhen(text, ctx.now, ctx.timeZone);
59
+ // "make it Friday please": the date plus only filler around it.
60
+ const spare = part ? contentWords(part.rest).filter((w) => !['make', 'set', 'put', 'move', 'due', 'say', 'lets', "let's", 'let', 'be', 'it', 'is', 'would', 'will', 'can'].includes(w)) : [];
61
+ const when = whole ?? (part && spare.length === 0 ? part.when : null);
62
+ if (!when) return unclear(`${q.question} You can say a day, like tomorrow or next Friday, or skip it.`);
63
+ return { kind: 'answer', value: when.date ?? '', spoken: when.later ? 'no date' : when.label };
64
+ }
65
+
66
+ function parseChoice(q: OpenQuestion, text: string, ctx: AnswerContext): SpokenAnswer {
67
+ const offered = offeredOptions(q, ctx.options);
68
+ const pool = ctx.options.length ? ctx.options : offered;
69
+ const asItems = (os: AnswerOption[]) => os.map((o) => ({ id: o.value, title: o.label }));
70
+
71
+ const hit = (o: AnswerOption): SpokenAnswer => ({ kind: 'answer', value: o.value, label: o.label, spoken: o.label });
72
+ const byValue = new Map(pool.map((o) => [o.value, o]));
73
+
74
+ // By name first: "that's the marketing project", "operations".
75
+ const named = matchItems(text.replace(CHOICE_FILLER, ' '), asItems(pool));
76
+ if (named.kind === 'one') return hit(byValue.get(named.item.id) as AnswerOption);
77
+ if (named.kind === 'many') {
78
+ const labels = named.items.map((i) => i.title);
79
+ return unclear(`Which one: ${orList(labels)}?`);
80
+ }
81
+ // Then by position among what was just offered: "the second one".
82
+ const position = ORDINALS.find(([re]) => re.test(text));
83
+ if (position && offered[position[1]]) return hit(offered[position[1]]);
84
+
85
+ const shown = offered.slice(0, 3).map((o) => speakable(o.label, 6));
86
+ return unclear(shown.length ? `I did not catch which. Is it ${orList(shown)}?` : 'I did not catch that. Can you say it again?');
87
+ }
88
+
89
+ export function parseSpokenAnswer(q: OpenQuestion, utterance: string, ctx: AnswerContext): SpokenAnswer {
90
+ const text = normalizeSpeech(utterance).replace(LEAD, '').trim();
91
+ if (!text) return unclear('Sorry, I did not catch that. Can you say that again?');
92
+ if (UNDO.test(text)) return { kind: 'undo' };
93
+ if (SKIP.test(text)) return { kind: 'skip' };
94
+ if (YES.test(text)) {
95
+ return q.assumed?.value || q.assumed?.display ? { kind: 'accept' } : unclear(`I do not have a guess for that one. ${q.question}`);
96
+ }
97
+ return q.kind === 'due_date' ? parseDate(q, text, ctx) : parseChoice(q, text, ctx);
98
+ }
@@ -0,0 +1,225 @@
1
+ /**
2
+ * ANSWER A CLARIFYING QUESTION BY VOICE, AND KEEP THE CONVERSATION GOING
3
+ * (bd startsim-tmrvi.5).
4
+ *
5
+ * words (transcribed if audio) -> which question (the one named, else the best open one)
6
+ * -> parse (its own grammar, `voice-parse`) -> apply through `answerQuestion`
7
+ * -> say it back AND ask the next question, so one press can lead to the next.
8
+ *
9
+ * Request-free like the briefing reply: a route, a worker and a test call the same thing.
10
+ * A repeat press (same `clientActionId`) is answered from the log; nothing runs twice.
11
+ */
12
+ import { speakConfirmation } from '../briefing/actions/confirm';
13
+ import type { ActionLog, ActionLogStore, PendingReply } from '../briefing/actions/types';
14
+ import type { BriefingAudio, BriefingSynthesize } from '../briefing/generate';
15
+ import { speakable } from '../briefing/speak';
16
+ import { answerQuestion, type AnswerDeps } from './answer';
17
+ import { close, listOpenQuestions, storeFor } from './sync';
18
+ import type { OpenQuestion, QuestionAnswer } from './types';
19
+ import { parseSpokenAnswer, type AnswerOption } from './voice-parse';
20
+
21
+ export const CLIENT_ACTION_ID = /^[A-Za-z0-9_-]{8,64}$/;
22
+ const SNOOZE_MS = 12 * 3_600_000;
23
+ const UNDO_WINDOW_MS = 30 * 60_000;
24
+ const PENDING_KEPT = 12;
25
+ export const MAX_ANSWER_AUDIO_BYTES = 10 * 1024 * 1024;
26
+
27
+ export class VoiceAnswerError extends Error {
28
+ constructor(message: string, readonly status: number, readonly code?: string) {
29
+ super(message);
30
+ this.name = 'VoiceAnswerError';
31
+ }
32
+ }
33
+
34
+ export interface VoiceAnswerDeps extends AnswerDeps {
35
+ /** The choices a project / team / owner answer may name. */
36
+ options(q: OpenQuestion): Promise<AnswerOption[]>;
37
+ log: ActionLogStore;
38
+ transcribe?: (input: { audio: Uint8Array; mimeType: string; hints: string[] }) => Promise<string>;
39
+ synthesize?: BriefingSynthesize;
40
+ audio?: Pick<BriefingAudio, 'put'>;
41
+ /** Where the spoken confirmation is fetched from, for this press. */
42
+ audioPath?: (clientActionId: string) => string;
43
+ timeZone?: string;
44
+ }
45
+
46
+ export interface VoiceAnswerRequest {
47
+ clientActionId: string;
48
+ /** The question being answered; omit to answer the best open one. */
49
+ questionId?: string;
50
+ utterance?: string;
51
+ audio?: { audio: Uint8Array; mimeType: string };
52
+ timeZone?: string;
53
+ }
54
+
55
+ export interface VoiceAnswerResult {
56
+ /** `clarify`: it asked back instead of acting. */
57
+ kind: 'answered' | 'accepted' | 'skipped' | 'undone' | 'clarify' | 'nothing';
58
+ clientActionId: string;
59
+ utterance: string;
60
+ /** The question this press answered (absent for `clarify` on nothing, `nothing`). */
61
+ question: OpenQuestion | null;
62
+ /** The next thing to ask, so the app can listen again with this id. */
63
+ next: OpenQuestion | null;
64
+ /** The sentence said back, including the next question. */
65
+ spoken: string;
66
+ audioUrl: string | null;
67
+ mimeType?: string;
68
+ /** Open questions still waiting. */
69
+ remaining: number;
70
+ replayed: boolean;
71
+ }
72
+
73
+ export function validateAnswerRequest(req: VoiceAnswerRequest): void {
74
+ if (!CLIENT_ACTION_ID.test(req.clientActionId ?? '')) {
75
+ throw new VoiceAnswerError('Send a clientActionId (8-64 letters, digits, - or _), fresh for each press.', 400);
76
+ }
77
+ if (req.utterance === undefined && !req.audio) throw new VoiceAnswerError('Send what was said: audio or an utterance.', 400);
78
+ if (req.audio && req.audio.audio.byteLength > MAX_ANSWER_AUDIO_BYTES) throw new VoiceAnswerError('That recording is too long for an answer.', 413);
79
+ }
80
+
81
+ const asks = (q: OpenQuestion, title: string) => {
82
+ const t = speakable(title, 10);
83
+ return t ? `About ${t}: ${q.question}` : q.question;
84
+ };
85
+
86
+ async function titleOf(deps: VoiceAnswerDeps, q: OpenQuestion): Promise<string> {
87
+ return (await deps.seam.load(q.itemId).catch(() => null))?.title ?? '';
88
+ }
89
+
90
+ function saidBack(q: OpenQuestion, title: string, a: { value: string; label?: string; spoken: string }): string {
91
+ const t = speakable(title, 8) || 'that one';
92
+ switch (q.kind) {
93
+ case 'due_date': return a.value ? `Got it, ${t} is due ${a.spoken}.` : `Got it, ${t} has no due date.`;
94
+ case 'project': return `Got it, ${t} goes under ${a.spoken}.`;
95
+ case 'team': return `Got it, ${t} goes to ${a.spoken}.`;
96
+ case 'ownership': return `Got it, ${t} is ${a.spoken}'s.`;
97
+ case 'private_space': return `Got it, ${a.spoken} is your private space.`;
98
+ }
99
+ }
100
+
101
+ async function recordPress(deps: VoiceAnswerDeps, entry: PendingReply) {
102
+ const log: ActionLog = await deps.log.load();
103
+ log.pending = [...(log.pending ?? []).filter((p) => p.id !== entry.id), entry].slice(-PENDING_KEPT);
104
+ await deps.log.save(log);
105
+ }
106
+
107
+ async function undoLast(deps: VoiceAnswerDeps, now: number): Promise<{ text: string; question: OpenQuestion | null }> {
108
+ const all = await storeFor(deps).all();
109
+ const last = all
110
+ .filter((q) => q.resolution === 'answered' && q.answer?.via && q.resolvedAt && now - Date.parse(q.resolvedAt) <= UNDO_WINDOW_MS)
111
+ .sort((a, b) => (b.resolvedAt ?? '').localeCompare(a.resolvedAt ?? ''))[0];
112
+ if (!last) return { text: 'There is nothing to undo.', question: null };
113
+ if (last.kind !== 'due_date' || !last.answer?.prior) {
114
+ return { text: 'I cannot undo that one by voice. You can change it on the item.', question: last };
115
+ }
116
+ const item = await deps.seam.load(last.itemId);
117
+ if (!item) return { text: 'That item is gone, so there is nothing to put back.', question: last };
118
+ await deps.seam.update(item, { dueAt: last.answer.prior.dueAt ?? null });
119
+ const at = new Date(now).toISOString();
120
+ const reopened = await storeFor(deps).put(last.itemId, last.kind, last.question, {
121
+ status: 'open', resolution: '', resolved_at: '', answer: '', updated_at: at,
122
+ });
123
+ return { text: `Undone. ${speakable(item.title, 8)} is back how it was.`, question: reopened };
124
+ }
125
+
126
+ export async function answerQuestionByVoice(deps: VoiceAnswerDeps, req: VoiceAnswerRequest): Promise<VoiceAnswerResult> {
127
+ validateAnswerRequest(req);
128
+ const now = (deps.now ?? Date.now)();
129
+ const id = req.clientActionId;
130
+ const timeZone = req.timeZone || deps.timeZone || 'UTC';
131
+ const store = storeFor(deps);
132
+
133
+ // Already handled: answer from the log.
134
+ const log = await deps.log.load();
135
+ const mine = (log.pending ?? []).find((p) => p.id === id);
136
+ const result = (over: Partial<VoiceAnswerResult> & Pick<VoiceAnswerResult, 'kind' | 'spoken'>, audio?: { audioUrl: string | null; mimeType?: string }): VoiceAnswerResult => ({
137
+ clientActionId: id, utterance: req.utterance ?? '', question: null, next: null, audioUrl: audio?.audioUrl ?? null,
138
+ ...(audio?.mimeType ? { mimeType: audio.mimeType } : {}), remaining: 0, replayed: false, ...over,
139
+ });
140
+ if (mine?.understood) {
141
+ const remaining = (await listOpenQuestions(deps)).length;
142
+ return result({
143
+ kind: mine.actions.some((a) => a.type === 'clarify') ? 'clarify' : 'answered', spoken: mine.understood, utterance: mine.utterance,
144
+ remaining, replayed: true,
145
+ }, { audioUrl: mine.confirmAudio && deps.audioPath ? deps.audioPath(id) : null, ...(mine.confirmAudio ? { mimeType: mine.confirmAudio.mimeType } : {}) });
146
+ }
147
+
148
+ const open = await listOpenQuestions(deps);
149
+ const target = req.questionId ? await store.get(req.questionId) : open[0] ?? null;
150
+ if (req.questionId && !target) throw new VoiceAnswerError('Not found.', 404);
151
+
152
+ let utterance = req.utterance ?? '';
153
+ if (req.audio) {
154
+ if (!deps.transcribe) throw new VoiceAnswerError('Speech to text is not set up.', 503, 'transcription_unavailable');
155
+ try {
156
+ const options = target ? await deps.options(target).catch(() => []) : [];
157
+ utterance = await deps.transcribe({ audio: req.audio.audio, mimeType: req.audio.mimeType, hints: options.map((o) => o.label) });
158
+ } catch (error) {
159
+ throw new VoiceAnswerError(`I could not make out the recording: ${error instanceof Error ? error.message : 'transcription failed'}`, 502, 'transcription_failed');
160
+ }
161
+ }
162
+ utterance = utterance.trim();
163
+
164
+ const finish = async (
165
+ kind: VoiceAnswerResult['kind'], lead: string, answered: OpenQuestion | null, asked: OpenQuestion | null = null,
166
+ ): Promise<VoiceAnswerResult> => {
167
+ const remainingQs = (await listOpenQuestions(deps)).filter((q) => q.id !== answered?.id || kind === 'undone');
168
+ const next = asked ?? (kind === 'clarify' ? null : remainingQs.find((q) => q.id !== answered?.id) ?? null);
169
+ const tail = kind === 'clarify' ? '' : next ? ` ${asks(next, await titleOf(deps, next))}` : ' That is everything for now.';
170
+ const spoken = `${lead}${tail}`.trim();
171
+ const said = await speakConfirmation({
172
+ text: spoken, clientActionId: id, synthesize: deps.synthesize,
173
+ audio: deps.audio && deps.audioPath ? { put: deps.audio.put, url: async (ref) => { audioRef = ref; return (deps.audioPath as (i: string) => string)(id); } } : undefined,
174
+ });
175
+ await recordPress(deps, {
176
+ id, utterance, understood: spoken, source: 'grammar', confidence: 1, at: new Date(now).toISOString(),
177
+ actions: kind === 'clarify' ? [{ type: 'clarify', question: spoken }] : [{ type: 'none' }],
178
+ ...(said.audioUrl && audioRef ? { confirmAudio: { ref: audioRef, mimeType: said.mimeType ?? 'audio/mpeg' } } : {}),
179
+ });
180
+ return result({ kind, spoken, question: answered, next, remaining: remainingQs.length, utterance }, said);
181
+ };
182
+ let audioRef = '';
183
+
184
+ if (!utterance) return finish('clarify', 'Sorry, I did not catch that. Can you say that again?', null);
185
+
186
+ const parsed = target
187
+ ? parseSpokenAnswer(target, utterance, { now, timeZone, options: await deps.options(target).catch(() => []) })
188
+ : parseSpokenAnswer({ id: '', itemId: '', kind: 'due_date', question: '', status: 'open', candidates: [], score: 0, ownerSub: deps.ownerSub, createdAt: '', updatedAt: '' }, utterance, { now, timeZone, options: [] });
189
+
190
+ if (parsed.kind === 'undo') {
191
+ const undone = await undoLast(deps, now);
192
+ return finish(undone.question && undone.text.startsWith('Undone') ? 'undone' : 'clarify', undone.text, undone.question, undone.question && undone.text.startsWith('Undone') ? undone.question : null);
193
+ }
194
+ if (!target) return finish('nothing', 'Nothing is waiting on you right now.', null);
195
+ const at = new Date(now).toISOString();
196
+ const title = await titleOf(deps, target);
197
+
198
+ switch (parsed.kind) {
199
+ case 'unclear': return finish('clarify', parsed.question, target);
200
+ case 'skip': {
201
+ const closed = await close(store, target, 'expired', 'skipped', at);
202
+ await store.put(target.itemId, target.kind, target.question, { snoozed_until: new Date(now + SNOOZE_MS).toISOString() });
203
+ return finish('skipped', 'Okay, I will ask again later.', closed);
204
+ }
205
+ case 'accept': {
206
+ const value = target.assumed?.value ?? '';
207
+ if (!value) return finish('clarify', `I do not have a guess to keep. ${target.question}`, target);
208
+ const named = target.assumed?.display ?? (await deps.options(target).catch(() => [])).find((o) => o.value === value)?.label;
209
+ const answered = await applyAnswer(deps, target, { value, ...(named ? { label: named } : {}), via: id });
210
+ // An id is not worth saying aloud: without a name, just confirm.
211
+ const said = target.kind === 'due_date' && named === undefined ? '' : named ? ` ${speakable(title, 8) || 'That one'} stays ${named}.` : '';
212
+ return finish('accepted', `Okay, keeping it.${said}`, answered);
213
+ }
214
+ case 'answer': {
215
+ const answered = await applyAnswer(deps, target, { value: parsed.value, ...(parsed.label ? { label: parsed.label } : {}), via: id });
216
+ return finish('answered', saidBack(target, title, parsed), answered);
217
+ }
218
+ }
219
+ }
220
+
221
+ /** Apply the answer, remembering what a due date was so "undo" can put it back. */
222
+ async function applyAnswer(deps: VoiceAnswerDeps, q: OpenQuestion, answer: QuestionAnswer): Promise<OpenQuestion> {
223
+ const prior = q.kind === 'due_date' ? await deps.seam.load(q.itemId).catch(() => null) : null;
224
+ return answerQuestion(deps, q.id, prior ? { ...answer, prior: { dueAt: prior.dueAt ?? null } } : answer);
225
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * THE TRACKER TIMELINE'S SERVER READS.
3
+ *
4
+ * Per series, ONE grouped count over the tenant's `entities/counts` (one row per
5
+ * stored date value, followed through its pages) plus ONE capped page of the
6
+ * rows themselves, for the table under the chart. Nothing here walks the list:
7
+ * the browser never holds more than 200 rows per series, and says so when a
8
+ * series had more (`truncated`).
9
+ *
10
+ * The counts are exact; the rows are the newest page. That asymmetry is
11
+ * deliberate and surfaced, not hidden: a chart that is right and a table that
12
+ * says "showing 200 of 450" beats a table that silently stops.
13
+ */
14
+ import type { CorpusHttp } from './client';
15
+ import {
16
+ anchorOf,
17
+ estimatedDoneParams,
18
+ timelineParams,
19
+ type TimelineFilter,
20
+ type TimelineInput,
21
+ type TimelineKind,
22
+ type ValueCount,
23
+ } from './tracker-timeline';
24
+ import type { CommitmentStatus } from './types';
25
+
26
+ const PAGE = 200;
27
+ /** Distinct stored values in a 90-day window stay far under this; it is a stop, not a target. */
28
+ const MAX_COUNT_PAGES = 10;
29
+ const STATUSES = ['open', 'in_progress', 'done', 'blocked', 'dropped'];
30
+
31
+ export interface TimelineReaderOptions {
32
+ http: Pick<CorpusHttp, 'get'>;
33
+ /** The commitment type key. */
34
+ type: string;
35
+ entitiesPath?: string;
36
+ }
37
+
38
+ export interface TimelineRead extends TimelineInput {
39
+ /** A series had more rows than the one page read for it. */
40
+ truncated: boolean;
41
+ }
42
+
43
+ interface Wire { id?: unknown; name?: unknown; updated_at?: unknown; updatedAt?: unknown; data?: unknown }
44
+
45
+ const text = (data: Record<string, unknown>, ...keys: string[]): string | null => {
46
+ for (const k of keys) {
47
+ const v = data[k];
48
+ if (typeof v === 'string' && v) return v;
49
+ }
50
+ return null;
51
+ };
52
+
53
+ function toItem(row: Wire) {
54
+ const data = row.data && typeof row.data === 'object' ? (row.data as Record<string, unknown>) : {};
55
+ const status = String(data.status ?? 'open');
56
+ return {
57
+ id: String(row.id),
58
+ title: text(data, 'title') ?? (typeof row.name === 'string' && row.name ? row.name : 'Untitled item'),
59
+ status: (STATUSES.includes(status) ? status : 'open') as CommitmentStatus,
60
+ dueAt: text(data, 'due_at', 'dueAt'),
61
+ firstSeenAt: text(data, 'first_seen_at', 'firstSeenAt'),
62
+ resolvedAt: text(data, 'resolved_at', 'resolvedAt'),
63
+ updatedAt: text(row as Record<string, unknown>, 'updated_at', 'updatedAt'),
64
+ };
65
+ }
66
+
67
+ export function createTimelineReader(options: TimelineReaderOptions) {
68
+ const entities = options.entitiesPath ?? 'api/v1/entities';
69
+ const { http, type } = options;
70
+
71
+ async function counts(params: Record<string, unknown> | null): Promise<ValueCount[]> {
72
+ if (!params) return [];
73
+ const out: ValueCount[] = [];
74
+ for (let page = 1; page <= MAX_COUNT_PAGES; page += 1) {
75
+ const body = await http.get<{ results?: Array<{ values?: unknown[]; count?: number }>; next?: string | null }>(
76
+ `${entities}/counts`, { params: { ...params, type, page, page_size: PAGE } });
77
+ for (const row of body.results ?? []) {
78
+ const v = row.values?.[0];
79
+ out.push({ value: typeof v === 'string' ? v : null, count: Number(row.count ?? 0) });
80
+ }
81
+ if (!body.next) break;
82
+ }
83
+ return out;
84
+ }
85
+
86
+ async function rows(params: Record<string, unknown> | null, order?: string) {
87
+ if (!params) return { items: [], truncated: false };
88
+ const { group_by: _g, ...rest } = params;
89
+ void _g;
90
+ const body = await http.get<{ count?: number; results?: Wire[] }>(
91
+ entities, { params: { ...rest, type, page_size: PAGE, ...(order ? { order } : {}) } });
92
+ const results = body.results ?? [];
93
+ return { items: results.map(toItem), truncated: Number(body.count ?? results.length) > results.length };
94
+ }
95
+
96
+ return async function read(
97
+ filter: TimelineFilter,
98
+ clock: { now: number; timeZone?: string },
99
+ ): Promise<TimelineRead> {
100
+ const p = (kind: TimelineKind) => timelineParams(kind, filter, clock);
101
+ const [created, done, overdue, rc, rd, re, ro] = await Promise.all([
102
+ counts(p('created')), counts(p('done')), counts(p('overdue')),
103
+ rows(p('created'), '-attr.first_seen_at'),
104
+ rows(p('done'), '-attr.resolved_at'),
105
+ rows(estimatedDoneParams(filter, clock)),
106
+ rows(p('overdue'), 'attr.due_at'),
107
+ ]);
108
+ const seen = new Map<string, ReturnType<typeof toItem>>();
109
+ for (const item of [...rc.items, ...rd.items, ...re.items, ...ro.items]) if (!seen.has(item.id)) seen.set(item.id, item);
110
+ return {
111
+ anchor: anchorOf(clock.now, clock.timeZone),
112
+ created, done, overdue,
113
+ items: [...seen.values()],
114
+ truncated: rc.truncated || rd.truncated || re.truncated || ro.truncated,
115
+ };
116
+ };
117
+ }