@startsimpli/integrations 0.2.222 → 0.2.224

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.
Files changed (58) hide show
  1. package/package.json +8 -8
  2. package/src/__tests__/attention-policy.test.ts +174 -0
  3. package/src/__tests__/attention-rhythm.test.ts +95 -0
  4. package/src/__tests__/attention-run.test.ts +123 -0
  5. package/src/__tests__/attention-settings-page.test.tsx +57 -0
  6. package/src/__tests__/attention-settings.test.ts +86 -0
  7. package/src/__tests__/converse-client.test.ts +6 -0
  8. package/src/__tests__/converse-meeting.test.ts +40 -0
  9. package/src/__tests__/converse-relay.test.ts +35 -0
  10. package/src/__tests__/converse-soak.test.ts +61 -0
  11. package/src/__tests__/converse-watchdog.test.ts +107 -0
  12. package/src/__tests__/decisions-page.test.tsx +1 -1
  13. package/src/__tests__/fleet-view.test.ts +1 -1
  14. package/src/components/index.ts +1 -0
  15. package/src/components/pages/AttentionSettings.tsx +51 -0
  16. package/src/components/pages/DecisionsPage.tsx +13 -2
  17. package/src/corpus/attention/controller.ts +37 -0
  18. package/src/corpus/attention/index.ts +8 -0
  19. package/src/corpus/attention/policy.ts +59 -0
  20. package/src/corpus/attention/push.ts +47 -0
  21. package/src/corpus/attention/queue.ts +22 -0
  22. package/src/corpus/attention/rhythm.ts +69 -0
  23. package/src/corpus/attention/run-steps.ts +89 -0
  24. package/src/corpus/attention/run.ts +55 -0
  25. package/src/corpus/attention/settings.ts +80 -0
  26. package/src/corpus/attention/types.ts +63 -0
  27. package/src/corpus/converse/client.ts +3 -2
  28. package/src/corpus/converse/handle.ts +18 -3
  29. package/src/corpus/converse/meeting-config.ts +15 -1
  30. package/src/corpus/converse/meeting.ts +100 -8
  31. package/src/corpus/converse/respond.ts +12 -2
  32. package/src/corpus/converse/types.ts +11 -0
  33. package/src/corpus/index.ts +1 -0
  34. package/src/corpus/notify/client.ts +10 -2
  35. package/src/corpus/notify/handle.ts +9 -5
  36. package/src/corpus/notify/respond.ts +1 -1
  37. package/src/corpus/notify/state.ts +3 -0
  38. package/src/corpus/notify/types.ts +9 -0
  39. package/src/native/app/converseServices.ts +1 -0
  40. package/src/native/app/notifyServices.ts +8 -1
  41. package/src/native/app/registry.tsx +4 -2
  42. package/src/native/app/services.ts +1 -1
  43. package/src/native/converse/DriveScreen.tsx +47 -0
  44. package/src/native/converse/__tests__/driveScreen.test.tsx +54 -0
  45. package/src/native/converse/api.ts +1 -0
  46. package/src/native/converse/fake.ts +4 -0
  47. package/src/native/converse/index.ts +1 -0
  48. package/src/native/converse/io.ts +1 -0
  49. package/src/native/push/AttentionCard.tsx +44 -0
  50. package/src/native/push/DecisionsScreen.tsx +12 -2
  51. package/src/native/push/NeedsYouCard.tsx +42 -0
  52. package/src/native/push/__tests__/decisionsApp.test.tsx +12 -1
  53. package/src/native/push/__tests__/needsYou.test.tsx +106 -0
  54. package/src/native/push/fake.ts +12 -1
  55. package/src/native/push/index.ts +3 -0
  56. package/src/native/push/needsYou.ts +29 -0
  57. package/src/native/push/tab.tsx +4 -2
  58. package/src/native/talk/TalkTab.tsx +24 -2
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The needs-you BRIEFING as a small state machine (bd startsim-nd3qa): the assistant itself asks item i of n, waits for the
3
+ * answer, records it, moves on, and ends by saying what it did. Pure: the caller stores the run and speaks the text.
4
+ * Never a chat message: nothing here is ever shown as something the person said.
5
+ */
6
+ export interface RunItem { id: string; text: string; ref?: string }
7
+ export interface RunAnswer { answer: string; at: string }
8
+ export interface AttentionRunState {
9
+ conversation_id: string;
10
+ items: RunItem[];
11
+ index: number;
12
+ answers: Record<string, RunAnswer>;
13
+ /** Items he put off: they stay in the queue and are not asked again in this run. */
14
+ skipped: string[];
15
+ status: 'asking' | 'done';
16
+ started_at: string;
17
+ }
18
+ export interface RunReply { text: string; active: boolean; index: number; of: number; recorded?: { item: RunItem; answer: string } }
19
+
20
+ const YES = /^\s*(yes|yeah|yep|yup|sure|ok|okay|approve[d]?|go ahead|do it|affirmative|correct|please do)\b/i;
21
+ const NO = /^\s*(no|nope|nah|don'?t|do not|hold off|negative|reject)\b/i;
22
+ const SKIP = /\b(skip|later|not now|next one|pass|come back)\b/i;
23
+ const AGAIN = /\b(again|repeat|what was that|say that|come again|didn'?t (catch|hear))\b/i;
24
+ const STOP = /^\s*(stop|cancel|that(?:'?s| is) (all|it|enough)|done|enough|never ?mind)\b/i;
25
+
26
+ export type Heard = { kind: 'yes' | 'no' } | { kind: 'skip' } | { kind: 'again' } | { kind: 'stop' } | { kind: 'free'; text: string };
27
+
28
+ export function hear(utterance: string): Heard {
29
+ const u = utterance.trim();
30
+ if (STOP.test(u)) return { kind: 'stop' };
31
+ if (AGAIN.test(u)) return { kind: 'again' };
32
+ if (SKIP.test(u)) return { kind: 'skip' };
33
+ if (YES.test(u)) return { kind: 'yes' };
34
+ if (NO.test(u)) return { kind: 'no' };
35
+ return { kind: 'free', text: u };
36
+ }
37
+
38
+ const plain = (s: string) => s.replace(/\s+/g, ' ').replace(/[.?!]+$/, '').trim();
39
+ export const questionText = (run: Pick<AttentionRunState, 'items' | 'index'>): string => {
40
+ const item = run.items[run.index];
41
+ return `Question ${run.index + 1} of ${run.items.length}: ${plain(item.text)}. Yes or no?`;
42
+ };
43
+ const reply = (run: AttentionRunState, text: string, recorded?: RunReply['recorded']): RunReply => ({ text, active: run.status === 'asking', index: Math.min(run.index, run.items.length), of: run.items.length, ...(recorded ? { recorded } : {}) });
44
+
45
+ export function startRun(input: { conversationId: string; items: RunItem[]; now: string }): { run: AttentionRunState; reply: RunReply } {
46
+ const run: AttentionRunState = { conversation_id: input.conversationId, items: input.items, index: 0, answers: {}, skipped: [], status: input.items.length ? 'asking' : 'done', started_at: input.now };
47
+ if (!input.items.length) return { run, reply: reply(run, 'Nothing is waiting on you right now.') };
48
+ const n = input.items.length;
49
+ return { run, reply: reply(run, `${n === 1 ? 'One thing needs you.' : `${n} things need you, most important first.`} ${questionText(run)}`) };
50
+ }
51
+
52
+ function finish(run: AttentionRunState, lead: string): { run: AttentionRunState; reply: RunReply } {
53
+ const next: AttentionRunState = { ...run, status: 'done' };
54
+ const saved = Object.keys(next.answers).length;
55
+ const left = next.items.length - saved;
56
+ const tail = saved === 0 ? 'I did not record any answers.' : `I saved ${saved} answer${saved === 1 ? '' : 's'} in your queue.`;
57
+ const rest = left > 0 ? ` ${left} ${left === 1 ? 'item is' : 'items are'} still waiting in your queue.` : '';
58
+ return { run: next, reply: reply(next, `${lead} ${tail}${rest}`) };
59
+ }
60
+
61
+ /** One step on what he said. Returns the new run and what to say. */
62
+ export function stepRun(run: AttentionRunState, utterance: string, now: string): { run: AttentionRunState; reply: RunReply } {
63
+ if (run.status !== 'asking') return { run, reply: reply(run, 'That list is finished.') };
64
+ const heard = hear(utterance);
65
+ const item = run.items[run.index];
66
+ const advance = (r: AttentionRunState, lead: string, recorded?: RunReply['recorded']) => {
67
+ const nextIndex = r.index + 1;
68
+ if (nextIndex >= r.items.length) {
69
+ const done = finish({ ...r, index: nextIndex }, `${lead} That was the last one.`.trim());
70
+ return { run: done.run, reply: { ...done.reply, ...(recorded ? { recorded } : {}) } };
71
+ }
72
+ const moved = { ...r, index: nextIndex };
73
+ return { run: moved, reply: reply(moved, `${lead} ${questionText(moved)}`.trim(), recorded) };
74
+ };
75
+ switch (heard.kind) {
76
+ case 'again': return { run, reply: reply(run, questionText(run)) };
77
+ case 'stop': return finish(run, 'Okay, stopping here.');
78
+ case 'skip': return advance({ ...run, skipped: [...run.skipped, item.id] }, 'Okay, later.');
79
+ case 'free': {
80
+ if (!heard.text) return { run, reply: reply(run, `I did not catch that. ${questionText(run)}`) };
81
+ const answered = { ...run, answers: { ...run.answers, [item.id]: { answer: heard.text.slice(0, 500), at: now } } };
82
+ return advance(answered, 'Got it.', { item, answer: heard.text.slice(0, 500) });
83
+ }
84
+ default: {
85
+ const answered = { ...run, answers: { ...run.answers, [item.id]: { answer: heard.kind, at: now } } };
86
+ return advance(answered, heard.kind === 'yes' ? 'Yes, noted.' : 'No, noted.', { item, answer: heard.kind });
87
+ }
88
+ }
89
+ }
@@ -0,0 +1,55 @@
1
+ /** The stored needs-you briefing: start it from the real queue, take answers, record them in the queue, deliver decision answers. */
2
+ import { loadFleetSnapshot } from '../converse/fleet';
3
+ import { buildFleetView } from '../converse/fleet-view';
4
+ import { answerDecision, getDecision } from '../notify/handle';
5
+ import { loadState, saveState } from '../notify/state';
6
+ import type { NotifyDeps } from '../notify/types';
7
+ import { buildNeedsYou } from './queue';
8
+ import { startRun, stepRun, type RunReply } from './run-steps';
9
+ import { policyFrom } from './settings';
10
+
11
+ export interface AttentionRunApi {
12
+ /** Begins a briefing in this conversation; the reply is what the assistant says first. */
13
+ start(conversationId: string): Promise<RunReply>;
14
+ /** Takes what he said as the answer to the current question; null when no briefing is running in this conversation. */
15
+ answer(conversationId: string, utterance: string): Promise<RunReply | null>;
16
+ }
17
+
18
+ export function createAttentionRun(deps: Pick<NotifyDeps, 'http' | 'ownerSub' | 'now'>, opts: { batch?: number } = {}): AttentionRunApi {
19
+ const nowIso = () => new Date((deps.now ?? Date.now)()).toISOString();
20
+ return {
21
+ async start(conversationId) {
22
+ const state = await loadState(deps);
23
+ const snap = await loadFleetSnapshot(deps as never).catch(() => null);
24
+ const policy = policyFrom(state.attention);
25
+ const queue = buildNeedsYou({ view: snap?.inputs ? buildFleetView(snap.inputs) : null, decisions: state.decisions, policy, answered: state.answered });
26
+ const items = queue.items.filter((i) => i.class === 'urgent' || i.class === 'needs-answer').slice(0, opts.batch ?? policy.briefBatch).map((i) => ({ id: i.id, text: i.text, ...(i.ref ? { ref: i.ref } : {}) }));
27
+ const { run, reply } = startRun({ conversationId, items, now: nowIso() });
28
+ await saveState(deps as never, { ...state, attention_run: run });
29
+ return reply;
30
+ },
31
+ async answer(conversationId, utterance) {
32
+ const state = await loadState(deps);
33
+ const current = state.attention_run;
34
+ if (!current || current.status !== 'asking' || current.conversation_id !== conversationId) return null;
35
+ const { run, reply } = stepRun(current, utterance, nowIso());
36
+ let answered = state.answered;
37
+ if (reply.recorded) {
38
+ const { item, answer } = reply.recorded;
39
+ let delivered: 'decision' | undefined;
40
+ if (item.ref) {
41
+ // A decision with ONE question takes his answer directly; a longer one is only recorded here.
42
+ try {
43
+ const d = await getDecision(deps as never, item.ref);
44
+ if (d.questions.length === 1) { await answerDecision(deps as never, item.ref, { answer }); delivered = 'decision'; }
45
+ } catch (e) { console.error('[attention] could not deliver the answer to its decision', e); }
46
+ }
47
+ answered = { ...state.answered, [item.id]: { answer, at: nowIso(), conversation_id: conversationId, ...(item.ref ? { ref: item.ref } : {}), ...(delivered ? { delivered } : {}) } };
48
+ const keys = Object.keys(answered);
49
+ if (keys.length > 300) answered = Object.fromEntries(keys.slice(-300).map((k) => [k, answered![k]]));
50
+ }
51
+ await saveState(deps as never, { ...state, attention_run: run, ...(answered ? { answered } : {}) });
52
+ return reply;
53
+ },
54
+ };
55
+ }
@@ -0,0 +1,80 @@
1
+ /** What the person can tune, stored on their notify state: quiet mode and schedule, urgent words, call-me threshold, scope. */
2
+ import { NotifyError } from '../notify/types';
3
+ import { isQuiet, resolveAttentionPolicy, type QuietMode } from './policy';
4
+ import type { AttentionPolicy } from './types';
5
+
6
+ export interface StoredAttention {
7
+ quiet_mode?: QuietMode;
8
+ quiet?: Partial<AttentionPolicy['quiet']>;
9
+ urgent_words?: string[];
10
+ call_me_at?: number;
11
+ brief_hour?: number;
12
+ wrap_hour?: number;
13
+ notify_scope?: AttentionPolicy['notifyScope'];
14
+ }
15
+ export interface AttentionSettings {
16
+ quiet_mode: QuietMode;
17
+ quiet: AttentionPolicy['quiet'];
18
+ /** Quiet right now (manual mode over schedule). Read-only. */
19
+ quiet_active: boolean;
20
+ urgent_words: string[];
21
+ call_me_at: number;
22
+ /** Local hour of the morning batch and the end-of-day batch. */
23
+ brief_hour: number;
24
+ wrap_hour: number;
25
+ notify_scope: AttentionPolicy['notifyScope'];
26
+ }
27
+
28
+ export const policyFrom = (stored?: StoredAttention): AttentionPolicy => resolveAttentionPolicy({
29
+ ...(stored?.quiet ? { quiet: stored.quiet } : {}), ...(stored?.urgent_words ? { urgentWords: stored.urgent_words } : {}),
30
+ ...(stored?.call_me_at ? { callMeAt: stored.call_me_at } : {}),
31
+ ...(stored?.brief_hour !== undefined ? { brief: { hour: stored.brief_hour } } : {}), ...(stored?.wrap_hour !== undefined ? { wrap: { hour: stored.wrap_hour } } : {}), ...(stored?.notify_scope ? { notifyScope: stored.notify_scope } : {}),
32
+ });
33
+
34
+ export function settingsView(stored: StoredAttention | undefined, now: number): AttentionSettings {
35
+ const policy = policyFrom(stored);
36
+ const mode = stored?.quiet_mode ?? 'off';
37
+ return { quiet_mode: mode, quiet: policy.quiet, quiet_active: isQuiet(now, policy.quiet, mode), urgent_words: policy.urgentWords, call_me_at: policy.callMeAt, brief_hour: policy.brief.hour, wrap_hour: policy.wrap.hour, notify_scope: policy.notifyScope };
38
+ }
39
+
40
+ const bad = (m: string) => new NotifyError(m, 400);
41
+ const hour = (v: unknown, name: string) => { if (typeof v !== 'number' || !Number.isInteger(v) || v < 0 || v > 23) throw bad(`${name} must be an hour from 0 to 23.`); return v; };
42
+
43
+ /** Validates a partial update and merges it into what is stored. Unknown keys are ignored. */
44
+ export function mergeAttention(stored: StoredAttention | undefined, patch: unknown): StoredAttention {
45
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) throw bad('attention must be an object.');
46
+ const p = patch as Record<string, unknown>;
47
+ const out: StoredAttention = { ...stored };
48
+ if (p.quiet_mode !== undefined) {
49
+ if (p.quiet_mode !== 'auto' && p.quiet_mode !== 'on' && p.quiet_mode !== 'off') throw bad('quiet_mode must be auto, on or off.');
50
+ out.quiet_mode = p.quiet_mode;
51
+ }
52
+ if (p.quiet !== undefined) {
53
+ if (!p.quiet || typeof p.quiet !== 'object') throw bad('quiet must be an object.');
54
+ const q = p.quiet as Record<string, unknown>;
55
+ const next: Partial<AttentionPolicy['quiet']> = { ...stored?.quiet };
56
+ if (q.enabled !== undefined) { if (typeof q.enabled !== 'boolean') throw bad('quiet.enabled must be true or false.'); next.enabled = q.enabled; }
57
+ if (q.start !== undefined) next.start = hour(q.start, 'quiet.start');
58
+ if (q.end !== undefined) next.end = hour(q.end, 'quiet.end');
59
+ if (q.timeZone !== undefined) {
60
+ try { new Intl.DateTimeFormat('en-US', { timeZone: String(q.timeZone) }); } catch { throw bad('quiet.timeZone is not a time zone.'); }
61
+ next.timeZone = String(q.timeZone);
62
+ }
63
+ out.quiet = next;
64
+ }
65
+ if (p.urgent_words !== undefined) {
66
+ if (!Array.isArray(p.urgent_words) || p.urgent_words.some((w) => typeof w !== 'string')) throw bad('urgent_words must be a list of words.');
67
+ out.urgent_words = [...new Set((p.urgent_words as string[]).map((w) => w.trim().toLowerCase()).filter(Boolean).map((w) => w.slice(0, 60)))].slice(0, 50);
68
+ }
69
+ if (p.call_me_at !== undefined) {
70
+ if (typeof p.call_me_at !== 'number' || !Number.isInteger(p.call_me_at) || p.call_me_at < 1 || p.call_me_at > 50) throw bad('call_me_at must be a whole number from 1 to 50.');
71
+ out.call_me_at = p.call_me_at;
72
+ }
73
+ if (p.brief_hour !== undefined) out.brief_hour = hour(p.brief_hour, 'brief_hour');
74
+ if (p.wrap_hour !== undefined) out.wrap_hour = hour(p.wrap_hour, 'wrap_hour');
75
+ if (p.notify_scope !== undefined) {
76
+ if (p.notify_scope !== 'decisions' && p.notify_scope !== 'decisions+fleet') throw bad('notify_scope must be decisions or decisions+fleet.');
77
+ out.notify_scope = p.notify_scope;
78
+ }
79
+ return out;
80
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Attention (bd startsim-nd3qa): what needs the person, how urgent it is, and when to interrupt them. Pure data and
3
+ * defaults; the answers still pending with Quinn (quiet hours, call-me threshold, brief and wrap times, whether fleet
4
+ * approvals ping, self-answering routine questions) are fields here, never constants in the logic.
5
+ */
6
+ export type AttentionClass = 'urgent' | 'needs-answer' | 'digest' | 'noise';
7
+ export type AttentionSource = 'fleet' | 'decision';
8
+
9
+ export interface AttentionItem { id: string; text: string; source: AttentionSource; /** The decision id, for an item that is a pending decision (opens its card). */ ref?: string }
10
+ export interface QueuedItem extends AttentionItem { class: AttentionClass }
11
+
12
+ export interface AttentionPolicy {
13
+ /** Which waiting items count as "needs you": his decisions only, or the fleet's approvals too. */
14
+ notifyScope: 'decisions' | 'decisions+fleet';
15
+ /** Hours (0-23) in the policy time zone; the window may wrap midnight. Urgent items ignore it, everything else waits. */
16
+ quiet: { enabled: boolean; start: number; end: number; timeZone: string };
17
+ /** This many waiting items (urgent included) earns one call-me push. */
18
+ callMeAt: number;
19
+ /** Daily rhythm (slice 5 reads these). */
20
+ brief: { hour: number };
21
+ wrap: { hour: number };
22
+ /** Answer continue / proceed questions without asking him (never an urgent one). */
23
+ selfAnswerRoutine: boolean;
24
+ /** Case-insensitive RegExp sources: a pending decision matching one (and not urgent) is answered "yes, continue" for him. */
25
+ routinePatterns: string[];
26
+ /** Case-insensitive RegExp sources. A line matching an urgent pattern is urgent; one matching a noise pattern is noise (urgent wins). */
27
+ urgentPatterns: string[];
28
+ noisePatterns: string[];
29
+ /** Plain words the person adds (no regex): a line containing one is urgent. */
30
+ urgentWords: string[];
31
+ /** How many items one briefing asks at a time (a short stand-up). */
32
+ briefBatch: number;
33
+ /** Matches wait for the daily brief instead of asking now (optional asks, items on hold). Urgent and noise are decided first. */
34
+ digestPatterns: string[];
35
+ }
36
+
37
+ export type AttentionPolicyInput = Partial<Omit<AttentionPolicy, 'quiet' | 'brief' | 'wrap'>> & {
38
+ quiet?: Partial<AttentionPolicy['quiet']>; brief?: Partial<AttentionPolicy['brief']>; wrap?: Partial<AttentionPolicy['wrap']>;
39
+ };
40
+
41
+ export const ATTENTION_DEFAULTS: AttentionPolicy = {
42
+ notifyScope: 'decisions+fleet',
43
+ quiet: { enabled: true, start: 22, end: 7, timeZone: 'America/Los_Angeles' },
44
+ callMeAt: 3,
45
+ brief: { hour: 8 },
46
+ wrap: { hour: 18 },
47
+ selfAnswerRoutine: true,
48
+ routinePatterns: ['\\b(should|shall|can|may) (we|i) (continue|proceed|keep going|go on)\\b', '\\b(ok|okay) to (continue|proceed)\\b', '^\\s*(continue|proceed)\\?', "\\b(i am|i'm) going to\\b.*\\b(unless|if) you\\b"],
49
+ urgentPatterns: ['\\burgent\\b', '\\basap\\b', '\\boutage\\b', '\\bincident\\b', '\\b(prod|production)\\b.*\\bdown\\b', '\\bdown\\b.*\\b(prod|production)\\b', '\\bpayment (failed|failing)\\b', '\\b(security|breach|leaked?)\\b', '\\bexpires? (today|tonight|in \\d+ ?(m|min|minutes|h|hours?))\\b', '\\bdeadline (today|tonight)\\b'],
50
+ urgentWords: [],
51
+ briefBatch: 5,
52
+ digestPatterns: ['\\boptional\\b', '\\bhold\\b', '\\bstays? paused\\b', '\\bwhen (he|you) (is|are)? ?ready\\b'],
53
+ noisePatterns: ['^\\s*fyi\\b', '\\bno action (needed|required)\\b', '\\bnothing (needed|required) from you\\b', '\\bfor your information\\b', '\\b(should|shall|can|may) (we|i) (continue|proceed|keep going|go on)\\b', '\\b(ok|okay) to (continue|proceed)\\b', '^\\s*(continue|proceed)\\?'],
54
+ };
55
+
56
+ export interface NeedsYouQueue {
57
+ items: QueuedItem[];
58
+ counts: Record<AttentionClass, number>;
59
+ /** Enough are waiting that a call (Talk, batched) beats reading them one by one. */
60
+ callMe: boolean;
61
+ /** Waiting items that count toward the call-me threshold (urgent + needs-answer). */
62
+ waiting: number;
63
+ }
@@ -16,7 +16,7 @@ export class ConverseClientError extends Error {
16
16
  }
17
17
 
18
18
  export interface ConverseClient {
19
- turn(input: { audio?: Blob; text?: string; conversationId?: string; turnId?: string; timeZone?: string }): Promise<ConverseTurnResult>;
19
+ turn(input: { audio?: Blob; text?: string; briefing?: 'start'; conversationId?: string; turnId?: string; timeZone?: string }): Promise<ConverseTurnResult>;
20
20
  end(conversationId: string): Promise<ConverseEndResult>;
21
21
  /** The thread from turn `after` + 1 on: how a page finds out the relay wrote into it. */
22
22
  thread(conversationId: string, after: number): Promise<ConverseThread>;
@@ -47,10 +47,11 @@ export function createConverseClient(options: {
47
47
  }
48
48
 
49
49
  return {
50
- async turn({ audio, text, conversationId, turnId, timeZone }) {
50
+ async turn({ audio, text, briefing, conversationId, turnId, timeZone }) {
51
51
  const body = new FormData();
52
52
  if (audio) body.append('audio', audio, 'turn');
53
53
  if (text) body.append('text', text);
54
+ if (briefing) body.append('briefing', briefing);
54
55
  if (conversationId) body.append('conversation_id', conversationId);
55
56
  if (turnId) body.append('turn_id', turnId);
56
57
  body.append('timeZone', timeZone || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC');
@@ -44,17 +44,19 @@ const resultOf = (id: string, turn: ConverseTurn): ConverseTurnResult => ({
44
44
  audio_reason: turn.assistant.audio_ref ? null : (turn.assistant.audio_reason ?? 'no audio was produced'),
45
45
  ...(turn.intent ? { intent: turn.intent } : {}),
46
46
  ...(turn.sources?.length ? { sources: turn.sources } : {}),
47
+ ...(turn.attn ? { briefing: turn.attn } : {}),
47
48
  });
48
49
 
49
50
  function validate(req: ConverseTurnRequest) {
50
51
  if (req.conversationId !== undefined && !CLIENT_ID.test(req.conversationId)) throw new ConverseError('That conversation id is not valid.', 400);
51
52
  if (req.turnId !== undefined && !CLIENT_ID.test(req.turnId)) throw new ConverseError('turn_id must be 8-64 letters, digits, - or _.', 400);
52
- if (!req.text?.trim() && !req.audio) throw new ConverseError('Send what was said: audio or text.', 400);
53
+ if (!req.text?.trim() && !req.audio && req.briefing !== 'start') throw new ConverseError('Send what was said: audio or text.', 400);
53
54
  if (req.audio && req.audio.audio.byteLength > MAX_CONVERSE_AUDIO_BYTES) throw new ConverseError('That recording is too long for one turn.', 413);
54
55
  }
55
56
 
56
57
  export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRequest): Promise<ConverseTurnResult> {
57
58
  validate(req);
59
+ if (req.briefing === 'start' && !deps.attentionRun) throw new ConverseError('Send what was said: audio or text.', 400);
58
60
  const now = (deps.now ?? Date.now)();
59
61
  const store = deps.store ?? createEntityConversationStore(deps.http, deps.ownerSub);
60
62
  const newId = deps.newId ?? (() => crypto.randomUUID());
@@ -88,11 +90,21 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
88
90
  try {
89
91
  utterance = (await deps.transcribe({ audio: req.audio.audio, mimeType: req.audio.mimeType, hints })).trim();
90
92
  } catch (error) {
93
+ if (error instanceof Error && /no speech providers|provider is not configured|not configured/i.test(error.message)) {
94
+ throw new ConverseError('Voice is not set up on this server. You can type instead.', 503, 'speech_unavailable');
95
+ }
91
96
  throw new ConverseError(`I could not make out the recording: ${error instanceof Error ? error.message : 'transcription failed'}`, 502, 'transcription_failed');
92
97
  }
93
98
  }
94
99
  lap('stt');
95
100
 
101
+ // 1b. The needs-you briefing: the assistant asks (start) or takes his answer to the current question.
102
+ let walk: Awaited<ReturnType<NonNullable<ConverseDeps['attentionRun']>['start']>> | null = null;
103
+ if (deps.attentionRun) {
104
+ if (req.briefing === 'start') walk = await deps.attentionRun.start(conversationId);
105
+ else if (utterance) walk = await deps.attentionRun.answer(conversationId, utterance);
106
+ }
107
+
96
108
  // 2. Answer.
97
109
  let replyText = NOT_HEARD;
98
110
  let did: string[] | undefined;
@@ -105,7 +117,10 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
105
117
  let briefing = record?.briefing;
106
118
  let context = record?.context;
107
119
  let pending: ConversationRecord['pending'];
108
- if (utterance) {
120
+ if (walk) {
121
+ replyText = walk.text;
122
+ intent = 'briefing';
123
+ } else if (utterance) {
109
124
  const lines = (record?.turns ?? []).flatMap((t) => [{ role: 'user' as const, text: t.user.text }, { role: 'assistant' as const, text: t.from === 'relay' ? `The relay said: ${t.assistant.text}` : t.assistant.text }]).filter((l) => l.text);
110
125
  const history = lines.slice(-(deps.historyLines ?? DEFAULT_HISTORY_LINES));
111
126
  try {
@@ -169,7 +184,7 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
169
184
  lap('tts');
170
185
 
171
186
  // 4. Save.
172
- const turn: ConverseTurn = { n, turn_id: turnId, at: new Date(now).toISOString(), user, assistant, ...(did ? { did } : {}), ...(forRelay ? { for_relay: true } : {}), ...(intent ? { intent } : {}), ...(sources?.length ? { sources } : {}) };
187
+ const turn: ConverseTurn = { n, turn_id: turnId, at: new Date(now).toISOString(), user, assistant, ...(did ? { did } : {}), ...(forRelay ? { for_relay: true } : {}), ...(intent ? { intent } : {}), ...(sources?.length ? { sources } : {}), ...(walk ? { attn: { active: walk.active, index: walk.index, of: walk.of } } : {}) };
173
188
  const base = endedRecord ?? record;
174
189
  const startedAt = base?.startedAt ?? turn.at;
175
190
  await store.save({
@@ -23,19 +23,33 @@ export interface MeetingConfig {
23
23
  resendMs: number;
24
24
  /** How often an open conversation asks whether the relay wrote into it. */
25
25
  relayPollMs: number;
26
+ /** Watchdog: a turn that has not come back after this long is dropped and sent again (same turn id). */
27
+ thinkingMaxMs: number;
28
+ /** Watchdog: a reply still "speaking" after this long is cut and listening resumes. */
29
+ speakingMaxMs: number;
30
+ /** Watchdog: a listen with no mic activity for this long is restarted. */
31
+ listenStallMs: number;
32
+ /** How often the watchdog looks. */
33
+ watchdogTickMs: number;
34
+ /** The microphone failed to start: try again after this long (up to 5 times in a row, then say so and stop). */
35
+ listenRetryMs: number;
36
+ /** The assistant's display name (greeting). Configuration, never hard-coded in a screen. */
37
+ assistantName: string;
26
38
  }
27
39
 
28
40
  export const MEETING_DEFAULTS: MeetingConfig = {
29
41
  silenceMs: 1200, minUtteranceMs: 400, maxUtteranceMs: 60_000, speechLevel: 0.02, speechStartMs: 150, bargeInLevel: 0.08,
30
42
  interruptOnSpeech: true, idleRotateMs: 30_000, relayPollMs: 4000, resendMs: 3000,
43
+ thinkingMaxMs: 25_000, speakingMaxMs: 120_000, listenStallMs: 15_000, watchdogTickMs: 1000, listenRetryMs: 1500, assistantName: 'Roci',
31
44
  };
32
45
 
33
46
  export function resolveMeetingConfig(over: Partial<MeetingConfig> = {}): MeetingConfig {
34
47
  const out: MeetingConfig = { ...MEETING_DEFAULTS };
35
- for (const key of ['silenceMs', 'minUtteranceMs', 'maxUtteranceMs', 'speechLevel', 'speechStartMs', 'bargeInLevel', 'idleRotateMs', 'relayPollMs', 'resendMs'] as const) {
48
+ for (const key of ['silenceMs', 'minUtteranceMs', 'maxUtteranceMs', 'speechLevel', 'speechStartMs', 'bargeInLevel', 'idleRotateMs', 'relayPollMs', 'resendMs', 'thinkingMaxMs', 'speakingMaxMs', 'listenStallMs', 'watchdogTickMs', 'listenRetryMs'] as const) {
36
49
  const v = over[key];
37
50
  if (typeof v === 'number' && Number.isFinite(v) && v > 0) out[key] = v;
38
51
  }
52
+ if (typeof over.assistantName === 'string' && over.assistantName.trim()) out.assistantName = over.assistantName.trim();
39
53
  if (typeof over.interruptOnSpeech === 'boolean') out.interruptOnSpeech = over.interruptOnSpeech;
40
54
  return out;
41
55
  }
@@ -43,7 +43,7 @@ export type ListenReason = 'speech-ended' | 'max-length' | 'no-speech' | 'cancel
43
43
 
44
44
  /** The part of the converse client the loop needs. `A` is the platform's recording (a Blob on the web, a file uri on iOS). */
45
45
  export interface MeetingApi<A = Blob> {
46
- turn(input: { audio?: A; text?: string; conversationId?: string; turnId?: string; timeZone?: string }): Promise<ConverseTurnResult>;
46
+ turn(input: { audio?: A; text?: string; briefing?: 'start'; conversationId?: string; turnId?: string; timeZone?: string }): Promise<ConverseTurnResult>;
47
47
  end(conversationId: string): Promise<ConverseEndResult>;
48
48
  /** Optional: without it the loop never looks for relay messages. */
49
49
  thread?(conversationId: string, after: number): Promise<ConverseThread>;
@@ -55,6 +55,8 @@ export interface MeetingReply { conversationId: string; turn: number; replyText:
55
55
  export interface ListenHooks {
56
56
  /** Called when the voice starts (a barge-in when the reply is being spoken). */
57
57
  onSpeechStart?: () => void;
58
+ /** Called on every mic level reading: proof the microphone is alive (the watchdog restarts a listen that goes silent). */
59
+ onActivity?: () => void;
58
60
  }
59
61
 
60
62
  export interface MeetingIO<A = Blob> {
@@ -77,11 +79,20 @@ export interface MeetingController {
77
79
  end(): Promise<ConverseEndResult | null>;
78
80
  replay(): Promise<void>;
79
81
  sendText(text: string): Promise<void>;
82
+ /** The assistant itself begins the needs-you briefing: it speaks the first question (no message from the person), then listens for the answer. */
83
+ startBriefing(): Promise<void>;
80
84
  dismissNotice(): void;
81
85
  state(): MeetingState;
82
86
  }
83
87
 
84
88
  const freshId = () => `m${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;
89
+ class TurnTimeout extends Error { constructor() { super('turn timed out'); } }
90
+ function withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {
91
+ return new Promise<T>((resolve, reject) => {
92
+ const t = setTimeout(() => reject(new TurnTimeout()), ms);
93
+ p.then((v) => { clearTimeout(t); resolve(v); }, (e) => { clearTimeout(t); reject(e); });
94
+ });
95
+ }
85
96
  const isRejected = (e: unknown) => e instanceof ConverseClientError && (e.status === 401 || e.status === 403 || e.status === 404 || e.status === 409);
86
97
 
87
98
  export function createMeetingController<A = Blob>(options: {
@@ -90,6 +101,8 @@ export function createMeetingController<A = Blob>(options: {
90
101
  config?: Partial<MeetingConfig>;
91
102
  timeZone?: string;
92
103
  onChange?: (state: MeetingState) => void;
104
+ /** Called when the watchdog healed a stuck state, for the diagnostics file. */
105
+ onHeal?: (event: string, fields?: Record<string, unknown>) => void;
93
106
  }): MeetingController {
94
107
  const { client, io } = options;
95
108
  const config = resolveMeetingConfig(options.config);
@@ -102,6 +115,10 @@ export function createMeetingController<A = Blob>(options: {
102
115
  let listenAbort = new AbortController();
103
116
  let speakAbort = new AbortController();
104
117
  let lastReply: MeetingReply | null = null;
118
+ /** The mic was turned on by a briefing (not by him): the end of the briefing turns it off again. */
119
+ let micForWalk = false;
120
+ // eslint-disable-next-line prefer-const
121
+ let ctl!: MeetingController;
105
122
  /** Bumped by stop(): a reply whose turn began before it is shown but not spoken. */
106
123
  let stopEpoch = 0;
107
124
  /** The newest turn number this meeting has seen, its own or the relay's. */
@@ -127,6 +144,31 @@ export function createMeetingController<A = Blob>(options: {
127
144
 
128
145
  /** True from the moment he starts talking until his utterance is handed over. */
129
146
  let userSpeaking = false;
147
+ let listenFailures = 0;
148
+
149
+ /** What the watchdog watches: when the current phase began and when the mic last showed life. */
150
+ let phaseSince = Date.now();
151
+ let lastPhase: MeetingPhase = 'idle';
152
+ let lastActivity = Date.now();
153
+ let wdTimer: ReturnType<typeof setInterval> | null = null;
154
+ const wdLog = (event: string, fields?: Record<string, unknown>) => options.onHeal?.(event, fields);
155
+ function watchdogTick() {
156
+ if (!running) return;
157
+ const t = Date.now();
158
+ if (s.phase !== lastPhase) { lastPhase = s.phase; phaseSince = t; }
159
+ if (s.phase === 'speaking' && t - phaseSince > config.speakingMaxMs) {
160
+ wdLog('speaking-stuck', { ms: t - phaseSince });
161
+ speakAbort.abort('watchdog');
162
+ set({ phase: restPhase() });
163
+ phaseSince = t;
164
+ } else if (s.phase === 'listening' && s.micOn && t - Math.max(phaseSince, lastActivity) > config.listenStallMs) {
165
+ wdLog('listen-stalled', { ms: t - Math.max(phaseSince, lastActivity) });
166
+ lastActivity = t;
167
+ listenAbort.abort('restart');
168
+ }
169
+ }
170
+ const startWatchdog = () => { if (!wdTimer) wdTimer = setInterval(watchdogTick, config.watchdogTickMs); };
171
+ const stopWatchdog = () => { if (wdTimer) clearInterval(wdTimer); wdTimer = null; };
130
172
 
131
173
  async function playReply(reply: MeetingReply) {
132
174
  // A reply (a relay message, a slow answer) never talks over him: wait until his utterance is over.
@@ -134,7 +176,10 @@ export function createMeetingController<A = Blob>(options: {
134
176
  speakAbort = new AbortController();
135
177
  set({ phase: 'speaking', noAudio: null });
136
178
  try {
137
- await io.speak(reply, speakAbort.signal, config);
179
+ // An io that ignores the abort must not hold the whole meeting: whichever comes first, the speech or the abort.
180
+ const signal = speakAbort.signal;
181
+ const aborted = new Promise<void>((resolve) => { if (signal.aborted) resolve(); else signal.addEventListener('abort', () => resolve(), { once: true }); });
182
+ await Promise.race([io.speak(reply, signal, config), aborted]);
138
183
  } catch (e) {
139
184
  set({ noAudio: `${e instanceof Error ? e.message : 'playback failed'}` });
140
185
  }
@@ -142,13 +187,13 @@ export function createMeetingController<A = Blob>(options: {
142
187
  }
143
188
 
144
189
  /** Sends one turn; resolves true when it produced a reply. Never throws except to stop the meeting. */
145
- async function takeTurn(input: { audio?: A; text?: string }, again?: string): Promise<boolean> {
190
+ async function takeTurn(input: { audio?: A; text?: string; briefing?: 'start' }, again?: string): Promise<boolean> {
146
191
  const turnId = again ?? freshId();
147
192
  const epoch = stopEpoch;
148
193
  set({ phase: 'thinking', error: null, retryable: false });
149
194
  for (let attempt = 0; attempt < 2; attempt += 1) {
150
195
  try {
151
- const out = await client.turn({ ...input, conversationId: s.conversationId ?? undefined, turnId, timeZone: options.timeZone });
196
+ const out = await withTimeout(client.turn({ ...input, conversationId: s.conversationId ?? undefined, turnId, timeZone: options.timeZone }), config.thinkingMaxMs);
152
197
  seen = Math.max(seen, out.turn);
153
198
  startPolling();
154
199
  // A recording with no words in it (a cough, a pause, the room): no line, no "sorry", no sound. Listen again.
@@ -156,9 +201,11 @@ export function createMeetingController<A = Blob>(options: {
156
201
  set({ conversationId: out.conversation_id });
157
202
  return true;
158
203
  }
204
+ // A briefing turn the assistant began itself has no words from him: nothing is shown as his message.
205
+ const hisWords = out.briefing && !out.transcript ? [] : [{ role: 'user' as const, text: out.transcript }];
159
206
  set({
160
207
  conversationId: out.conversation_id,
161
- lines: [...s.lines, { role: 'user', text: out.transcript }, { role: 'assistant', text: out.reply_text, ...(out.intent ? { intent: out.intent } : {}), ...(out.sources?.length ? { sources: out.sources } : {}) }],
208
+ lines: [...s.lines, ...hisWords, { role: 'assistant', text: out.reply_text, ...(out.intent ? { intent: out.intent } : {}), ...(out.sources?.length ? { sources: out.sources } : {}) }],
162
209
  });
163
210
  // The assistant wrapped the conversation up and filed it: a quiet line, and the next message starts a new conversation.
164
211
  if (out.ended) {
@@ -170,14 +217,31 @@ export function createMeetingController<A = Blob>(options: {
170
217
  if (out.audio_url) {
171
218
  lastReply = { conversationId: out.conversation_id, turn: out.turn, replyText: out.reply_text, audioUrl: out.audio_url };
172
219
  // A typed message speaks its reply even before Start: the person asked in text, but the screen is a voice one.
173
- if ((running || input.text) && epoch === stopEpoch) await playReply(lastReply);
220
+ if ((running || input.text || input.briefing) && epoch === stopEpoch) await playReply(lastReply);
174
221
  } else {
175
222
  lastReply = null;
176
223
  set({ noAudio: out.audio_reason ?? 'no audio was produced' });
177
224
  }
225
+ // A briefing keeps listening for his answers; when it finishes the mic goes off again and the screen is idle.
226
+ if (out.briefing?.active && !s.micOn) { micForWalk = true; setTimeout(() => ctl.mic(true), 0); }
227
+ else if (out.briefing && !out.briefing.active && micForWalk) { micForWalk = false; setTimeout(() => ctl.mic(false), 0); }
178
228
  return true;
179
229
  } catch (e) {
180
230
  if (isRejected(e)) { set({ phase: 'stopped', micOn: false, error: e instanceof Error ? e.message : 'The session ended.' }); running = false; return false; }
231
+ if (e instanceof ConverseClientError && e.code === 'speech_unavailable') {
232
+ // Voice cannot work here at all: say so once, stop listening, go idle. Nothing is resent (it would only fail the same way).
233
+ set({ phase: 'idle', micOn: false, micLive: false, retryable: false, error: e.message });
234
+ listenAbort.abort('stop');
235
+ return false;
236
+ }
237
+ if (e instanceof TurnTimeout) {
238
+ // The server never answered: heal silently. The same recording goes again (same turn id, so it never doubles); typed text is shown as failed.
239
+ wdLog('turn-timeout', { turnId });
240
+ set({ error: null, retryable: false });
241
+ if (input.audio && running) scheduleResend(input, turnId);
242
+ else if (!input.audio) set({ error: 'That did not go through. Try again.', retryable: true });
243
+ return false;
244
+ }
181
245
  if (attempt === 1 || !(e instanceof ConverseClientError && e.retryable)) {
182
246
  set({ error: e instanceof Error ? e.message : 'That turn failed.', retryable: e instanceof ConverseClientError && e.retryable });
183
247
  // What he said is never thrown away: the same recording is sent again (same turn id, so the server never doubles it).
@@ -252,13 +316,27 @@ export function createMeetingController<A = Blob>(options: {
252
316
  }
253
317
  listenAbort = new AbortController();
254
318
  if (!duplex || s.phase === 'idle') set({ phase: 'listening' });
255
- const heard = await io.listen(listenAbort.signal, config, {
319
+ lastActivity = Date.now();
320
+ let heard: Awaited<ReturnType<typeof io.listen>>;
321
+ try {
322
+ heard = await io.listen(listenAbort.signal, config, {
323
+ onActivity: () => { lastActivity = Date.now(); },
256
324
  // Barge-in: the person starts talking while the reply is being read: cut it off, what they say is the next turn.
257
325
  onSpeechStart: () => {
258
326
  userSpeaking = true;
259
327
  if (duplex && config.interruptOnSpeech && s.phase === 'speaking') speakAbort.abort('barge-in');
260
328
  },
261
329
  });
330
+ listenFailures = 0;
331
+ } catch (e) {
332
+ // The microphone failed to start (a route change, another app holding the session): never let that end the meeting. Try again; after 5 in a row say so.
333
+ userSpeaking = false;
334
+ listenFailures += 1;
335
+ wdLog('listen-failed', { error: e instanceof Error ? e.message : String(e), n: listenFailures });
336
+ if (listenFailures >= 5) { set({ phase: 'idle', micOn: false, micLive: false, error: e instanceof Error ? e.message : 'The microphone could not start.' }); continue; }
337
+ await new Promise((r) => setTimeout(r, config.listenRetryMs));
338
+ continue;
339
+ }
262
340
  userSpeaking = false;
263
341
  if (!running) break;
264
342
  // An io with no microphone cancels by itself: wait for End (typing still works) instead of spinning.
@@ -292,9 +370,10 @@ export function createMeetingController<A = Blob>(options: {
292
370
  }
293
371
  loop = run();
294
372
  startPolling();
373
+ startWatchdog();
295
374
  }
296
375
 
297
- return {
376
+ ctl = {
298
377
  state: () => s,
299
378
  getState: () => s,
300
379
  subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
@@ -332,6 +411,17 @@ export function createMeetingController<A = Blob>(options: {
332
411
  turnChain = gate;
333
412
  await done;
334
413
  },
414
+ async startBriefing() {
415
+ const done = turnChain.then(async () => {
416
+ if (running) pauseListening();
417
+ await takeTurn({ briefing: 'start' });
418
+ if (running && s.phase !== 'stopped') set({ phase: restPhase() });
419
+ else if (!running && (s.phase === 'thinking' || s.phase === 'speaking')) set({ phase: 'idle' });
420
+ });
421
+ gate = done.catch(() => undefined);
422
+ turnChain = gate;
423
+ await done;
424
+ },
335
425
  dismissNotice() { set({ relayNotice: null }); },
336
426
  async replay() {
337
427
  if (!lastReply) return;
@@ -349,6 +439,7 @@ export function createMeetingController<A = Blob>(options: {
349
439
  running = false;
350
440
  resume?.();
351
441
  stopPolling();
442
+ stopWatchdog();
352
443
  listenAbort.abort();
353
444
  speakAbort.abort();
354
445
  await loop?.catch(() => undefined);
@@ -365,4 +456,5 @@ export function createMeetingController<A = Blob>(options: {
365
456
  }
366
457
  },
367
458
  };
459
+ return ctl;
368
460
  }