@startsimpli/integrations 0.2.224 → 0.2.226

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 (66) hide show
  1. package/package.json +6 -6
  2. package/src/__tests__/attention-importance.test.ts +51 -0
  3. package/src/__tests__/attention-policy.test.ts +7 -7
  4. package/src/__tests__/attention-run.test.ts +15 -6
  5. package/src/__tests__/attention-settings.test.ts +3 -3
  6. package/src/__tests__/converse-meeting-interrupted.test.ts +74 -0
  7. package/src/__tests__/converse-roci-transcript.test.ts +36 -0
  8. package/src/__tests__/converse-roci.test.ts +16 -1
  9. package/src/__tests__/converse-tts.test.ts +128 -0
  10. package/src/__tests__/converse.test.ts +15 -0
  11. package/src/__tests__/relay-items.test.ts +89 -0
  12. package/src/corpus/attention/importance.ts +17 -0
  13. package/src/corpus/attention/index.ts +1 -0
  14. package/src/corpus/attention/policy.ts +3 -1
  15. package/src/corpus/attention/push.ts +1 -1
  16. package/src/corpus/attention/queue.ts +11 -7
  17. package/src/corpus/attention/run-steps.ts +3 -2
  18. package/src/corpus/attention/run.ts +15 -5
  19. package/src/corpus/attention/types.ts +17 -5
  20. package/src/corpus/converse/handle.ts +5 -2
  21. package/src/corpus/converse/meeting.ts +20 -3
  22. package/src/corpus/converse/respond.ts +1 -1
  23. package/src/corpus/converse/roci.ts +11 -4
  24. package/src/corpus/converse/speak-chunks.ts +33 -0
  25. package/src/corpus/converse/speak.ts +17 -4
  26. package/src/corpus/notify/index.ts +2 -0
  27. package/src/corpus/notify/relay-items.ts +53 -0
  28. package/src/corpus/notify/respond.ts +6 -0
  29. package/src/corpus/notify/state.ts +1 -0
  30. package/src/corpus/notify/types.ts +6 -1
  31. package/src/native/app/FoundryApp.tsx +36 -1
  32. package/src/native/app/__tests__/briefingServices.test.ts +26 -0
  33. package/src/native/app/__tests__/haptics.test.tsx +55 -0
  34. package/src/native/app/__tests__/launch.test.ts +20 -1
  35. package/src/native/app/briefingServices.ts +9 -0
  36. package/src/native/app/converseServices.ts +15 -4
  37. package/src/native/app/device.ts +4 -0
  38. package/src/native/app/launch.ts +20 -0
  39. package/src/native/app/services.ts +2 -2
  40. package/src/native/briefing/__tests__/playerPauseResume.test.ts +47 -0
  41. package/src/native/briefing/audioPlayer.ts +14 -0
  42. package/src/native/converse/__tests__/bargeInIO.test.ts +46 -0
  43. package/src/native/converse/__tests__/meetingIO.test.ts +89 -23
  44. package/src/native/converse/__tests__/mock.test.ts +58 -0
  45. package/src/native/converse/index.ts +2 -0
  46. package/src/native/converse/io.ts +34 -20
  47. package/src/native/converse/mock.ts +136 -0
  48. package/src/native/index.ts +1 -0
  49. package/src/native/recording/recorder.ts +2 -1
  50. package/src/native/recording/recorderAudio.ts +14 -1
  51. package/src/native/voice-session/__tests__/bargeIn.test.ts +93 -0
  52. package/src/native/voice-session/__tests__/bindings.test.ts +84 -0
  53. package/src/native/voice-session/__tests__/events.test.ts +72 -0
  54. package/src/native/voice-session/__tests__/inspector.test.ts +28 -0
  55. package/src/native/voice-session/__tests__/lifecycle.test.ts +197 -0
  56. package/src/native/voice-session/__tests__/music.test.ts +86 -0
  57. package/src/native/voice-session/__tests__/routes.test.ts +121 -0
  58. package/src/native/voice-session/__tests__/voiceSession.test.ts +177 -0
  59. package/src/native/voice-session/bindMeeting.ts +33 -0
  60. package/src/native/voice-session/fake.ts +21 -0
  61. package/src/native/voice-session/index.ts +142 -0
  62. package/src/native/voice-session/inspector.ts +14 -0
  63. package/src/native/voice-session/machine.ts +41 -0
  64. package/src/native/voice-session/nowPlaying.ts +35 -0
  65. package/src/native/voice-session/types.ts +45 -0
  66. package/src/native/voice-session/wire.ts +47 -0
@@ -24,7 +24,7 @@ export async function runAttention(deps: NotifyDeps, input: { view: Pick<FleetVi
24
24
  const autoAnswered = await answerRoutine(deps, policy);
25
25
  const state = autoAnswered.length ? await loadState(deps) : first;
26
26
  const now = input.now ?? (deps.now ?? Date.now)();
27
- const queue = buildNeedsYou({ view: input.view, decisions: state.decisions, policy, answered: state.answered });
27
+ const queue = buildNeedsYou({ view: input.view, decisions: state.decisions, policy, answered: state.answered, relay: state.relay_items });
28
28
  const pushed: AttentionPush[] = [];
29
29
 
30
30
  for (const it of queue.items.filter((i): i is QueuedItem => i.class === 'urgent')) {
@@ -1,22 +1,26 @@
1
1
  /** The "needs you" queue: the fleet's waiting-on-Quinn lines plus his pending decisions, classified. */
2
2
  import type { FleetView } from '../converse/fleet-view';
3
- import type { DecisionIndexRow } from '../notify/types';
3
+ import type { DecisionIndexRow, RelayItem } from '../notify/types';
4
+ import { importanceOf } from './importance';
4
5
  import { classifyItem, itemId } from './policy';
5
6
  import type { AttentionClass, AttentionItem, AttentionPolicy, NeedsYouQueue, QueuedItem } from './types';
6
7
 
7
8
  const ORDER: AttentionClass[] = ['urgent', 'needs-answer', 'digest', 'noise'];
8
9
  const clean = (s: string) => s.replace(/`|\*\*/g, '').replace(/\s+/g, ' ').trim();
9
10
 
10
- export function buildNeedsYou(input: { view: Pick<FleetView, 'waitingOnQuinn'> | null; decisions: DecisionIndexRow[]; policy: AttentionPolicy; /** Items already answered (by id): they leave the queue. */ answered?: Record<string, unknown> }): NeedsYouQueue {
11
- const raw: AttentionItem[] = [
11
+ export function buildNeedsYou(input: { view: Pick<FleetView, 'waitingOnQuinn'> | null; decisions: DecisionIndexRow[]; policy: AttentionPolicy; /** Items already answered (by id): they leave the queue. */ answered?: Record<string, unknown>; /** Questions the relay posted for him (their own list, never touched by the fleet snapshot). */ relay?: RelayItem[] }): NeedsYouQueue {
12
+ type Raw = Omit<AttentionItem, 'id'> & { id?: string };
13
+ const rawIn: Raw[] = [
14
+ ...(input.relay ?? []).map((r) => ({ id: `relay:${r.id}`, text: clean(r.text), source: 'relay' as const, ...(r.options?.length ? { options: r.options } : {}), ...(r.source ? { from: r.source } : {}), ...(r.link ? { link: r.link } : {}) })),
12
15
  ...input.decisions.filter((d) => d.status === 'pending').map((d) => ({ text: clean(d.title), source: 'decision' as const, ref: d.id })),
13
16
  ...(input.view?.waitingOnQuinn ?? []).map((t) => ({ text: clean(t), source: 'fleet' as const })),
14
- ].filter((i) => i.text).map((i) => ({ ...i, id: itemId(i.text) }));
17
+ ];
18
+ const raw: AttentionItem[] = rawIn.filter((i) => i.text).map((i) => ({ ...i, id: i.id ?? itemId(i.text) }));
15
19
  const seen = new Set<string>(Object.keys(input.answered ?? {}));
16
- const all: QueuedItem[] = raw.filter((i) => !seen.has(i.id) && seen.add(i.id)).map((i) => ({ ...i, class: classifyItem(i, input.policy) }));
20
+ const all: QueuedItem[] = raw.filter((i) => !seen.has(i.id) && seen.add(i.id)).map((i) => { const cls = classifyItem(i, input.policy); return { ...i, class: cls, importance: importanceOf(i, cls, input.policy) }; });
17
21
  const counts: Record<AttentionClass, number> = { urgent: 0, 'needs-answer': 0, digest: 0, noise: 0 };
18
22
  for (const i of all) counts[i.class] += 1;
19
- const items = all.filter((i) => i.class !== 'noise').sort((a, b) => ORDER.indexOf(a.class) - ORDER.indexOf(b.class));
20
- const waiting = counts.urgent + counts['needs-answer'];
23
+ const items = all.filter((i) => i.class !== 'noise').sort((a, b) => b.importance - a.importance || ORDER.indexOf(a.class) - ORDER.indexOf(b.class));
24
+ const waiting = all.filter((i) => (i.class === 'urgent' || i.class === 'needs-answer') && i.importance >= input.policy.callMeMinImportance).length;
21
25
  return { items, counts, callMe: waiting >= input.policy.callMeAt, waiting };
22
26
  }
@@ -3,7 +3,7 @@
3
3
  * answer, records it, moves on, and ends by saying what it did. Pure: the caller stores the run and speaks the text.
4
4
  * Never a chat message: nothing here is ever shown as something the person said.
5
5
  */
6
- export interface RunItem { id: string; text: string; ref?: string }
6
+ export interface RunItem { id: string; text: string; ref?: string; /** A choice instead of yes/no. */ options?: string[] }
7
7
  export interface RunAnswer { answer: string; at: string }
8
8
  export interface AttentionRunState {
9
9
  conversation_id: string;
@@ -38,7 +38,8 @@ export function hear(utterance: string): Heard {
38
38
  const plain = (s: string) => s.replace(/\s+/g, ' ').replace(/[.?!]+$/, '').trim();
39
39
  export const questionText = (run: Pick<AttentionRunState, 'items' | 'index'>): string => {
40
40
  const item = run.items[run.index];
41
- return `Question ${run.index + 1} of ${run.items.length}: ${plain(item.text)}. Yes or no?`;
41
+ const ask = item.options?.length ? `Say ${item.options.length === 2 ? item.options.join(' or ') : `${item.options.slice(0, -1).join(', ')} or ${item.options[item.options.length - 1]}`}.` : 'Yes or no?';
42
+ return `Question ${run.index + 1} of ${run.items.length}: ${plain(item.text)}. ${ask}`;
42
43
  };
43
44
  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
 
@@ -15,15 +15,19 @@ export interface AttentionRunApi {
15
15
  answer(conversationId: string, utterance: string): Promise<RunReply | null>;
16
16
  }
17
17
 
18
- export function createAttentionRun(deps: Pick<NotifyDeps, 'http' | 'ownerSub' | 'now'>, opts: { batch?: number } = {}): AttentionRunApi {
18
+ /** What the relay is told when he answers one of its questions. */
19
+ export interface RelayDelivery { id: string; text: string; answer: string; source?: string; link?: string }
20
+
21
+ export function createAttentionRun(deps: Pick<NotifyDeps, 'http' | 'ownerSub' | 'now'>, opts: { batch?: number; /** Tells the relay his answer (the server runs the bridge). A failure keeps the answer stored for the relay to read back. */ deliverRelay?: (d: RelayDelivery) => Promise<void> } = {}): AttentionRunApi {
19
22
  const nowIso = () => new Date((deps.now ?? Date.now)()).toISOString();
20
23
  return {
21
24
  async start(conversationId) {
22
25
  const state = await loadState(deps);
23
26
  const snap = await loadFleetSnapshot(deps as never).catch(() => null);
24
27
  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 } : {}) }));
28
+ const queue = buildNeedsYou({ view: snap?.inputs ? buildFleetView(snap.inputs) : null, decisions: state.decisions, policy, answered: state.answered, relay: state.relay_items });
29
+ // Fleet lines are prose, not questions: they stay in the queue (and still drive pushes) but are never asked as yes/no. The relay posts real questions through relay-items, with options.
30
+ const items = queue.items.filter((i) => i.source !== 'fleet' && (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 } : {}), ...(i.options?.length ? { options: i.options } : {}) }));
27
31
  const { run, reply } = startRun({ conversationId, items, now: nowIso() });
28
32
  await saveState(deps as never, { ...state, attention_run: run });
29
33
  return reply;
@@ -36,7 +40,13 @@ export function createAttentionRun(deps: Pick<NotifyDeps, 'http' | 'ownerSub' |
36
40
  let answered = state.answered;
37
41
  if (reply.recorded) {
38
42
  const { item, answer } = reply.recorded;
39
- let delivered: 'decision' | undefined;
43
+ let delivered: 'decision' | 'relay' | undefined;
44
+ let deliveryFailed = false;
45
+ const relayItem = item.id.startsWith('relay:') ? (state.relay_items ?? []).find((r) => `relay:${r.id}` === item.id) : undefined;
46
+ if (relayItem && opts.deliverRelay) {
47
+ try { await opts.deliverRelay({ id: relayItem.id, text: relayItem.text, answer, ...(relayItem.source ? { source: relayItem.source } : {}), ...(relayItem.link ? { link: relayItem.link } : {}) }); delivered = 'relay'; }
48
+ catch (e) { deliveryFailed = true; console.error('[attention] could not tell the relay his answer (kept for it to read back)', e); }
49
+ }
40
50
  if (item.ref) {
41
51
  // A decision with ONE question takes his answer directly; a longer one is only recorded here.
42
52
  try {
@@ -44,7 +54,7 @@ export function createAttentionRun(deps: Pick<NotifyDeps, 'http' | 'ownerSub' |
44
54
  if (d.questions.length === 1) { await answerDecision(deps as never, item.ref, { answer }); delivered = 'decision'; }
45
55
  } catch (e) { console.error('[attention] could not deliver the answer to its decision', e); }
46
56
  }
47
- answered = { ...state.answered, [item.id]: { answer, at: nowIso(), conversation_id: conversationId, ...(item.ref ? { ref: item.ref } : {}), ...(delivered ? { delivered } : {}) } };
57
+ answered = { ...state.answered, [item.id]: { answer, at: nowIso(), conversation_id: conversationId, ...(item.ref ? { ref: item.ref } : {}), ...(delivered ? { delivered } : {}), ...(relayItem ? { source: 'relay' as const } : {}), ...(deliveryFailed ? { delivery_failed: true } : {}) } };
48
58
  const keys = Object.keys(answered);
49
59
  if (keys.length > 300) answered = Object.fromEntries(keys.slice(-300).map((k) => [k, answered![k]]));
50
60
  }
@@ -4,10 +4,10 @@
4
4
  * approvals ping, self-answering routine questions) are fields here, never constants in the logic.
5
5
  */
6
6
  export type AttentionClass = 'urgent' | 'needs-answer' | 'digest' | 'noise';
7
- export type AttentionSource = 'fleet' | 'decision';
7
+ export type AttentionSource = 'fleet' | 'decision' | 'relay';
8
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 }
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; /** A relay item's choices ("schedule" or "manual"): asked as a choice, not yes/no. */ options?: string[]; /** Who asked, in plain words (a relay item's source project). */ from?: string; /** Where to look at it, when there is somewhere. */ link?: string }
10
+ export interface QueuedItem extends AttentionItem { class: AttentionClass; /** 0-100; urgent 100. Orders the queue and gates call-me. */ importance: number }
11
11
 
12
12
  export interface AttentionPolicy {
13
13
  /** Which waiting items count as "needs you": his decisions only, or the fleet's approvals too. */
@@ -16,6 +16,13 @@ export interface AttentionPolicy {
16
16
  quiet: { enabled: boolean; start: number; end: number; timeZone: string };
17
17
  /** This many waiting items (urgent included) earns one call-me push. */
18
18
  callMeAt: number;
19
+ /** An item must score at least this (see importance.ts) to count toward call-me; urgent always does. 0 counts every waiting item. */
20
+ callMeMinImportance: number;
21
+ /** Case-insensitive RegExp sources for what raises an item's importance: money, outward-facing actions, only he can provide. */
22
+ moneyPatterns: string[];
23
+ outwardPatterns: string[];
24
+ onlyYouPatterns: string[];
25
+ importanceWeights: { money: number; outward: number; onlyYou: number };
19
26
  /** Daily rhythm (slice 5 reads these). */
20
27
  brief: { hour: number };
21
28
  wrap: { hour: number };
@@ -34,14 +41,19 @@ export interface AttentionPolicy {
34
41
  digestPatterns: string[];
35
42
  }
36
43
 
37
- export type AttentionPolicyInput = Partial<Omit<AttentionPolicy, 'quiet' | 'brief' | 'wrap'>> & {
38
- quiet?: Partial<AttentionPolicy['quiet']>; brief?: Partial<AttentionPolicy['brief']>; wrap?: Partial<AttentionPolicy['wrap']>;
44
+ export type AttentionPolicyInput = Partial<Omit<AttentionPolicy, 'quiet' | 'brief' | 'wrap' | 'importanceWeights'>> & {
45
+ quiet?: Partial<AttentionPolicy['quiet']>; brief?: Partial<AttentionPolicy['brief']>; wrap?: Partial<AttentionPolicy['wrap']>; importanceWeights?: Partial<AttentionPolicy['importanceWeights']>;
39
46
  };
40
47
 
41
48
  export const ATTENTION_DEFAULTS: AttentionPolicy = {
42
49
  notifyScope: 'decisions+fleet',
43
50
  quiet: { enabled: true, start: 22, end: 7, timeZone: 'America/Los_Angeles' },
44
51
  callMeAt: 3,
52
+ callMeMinImportance: 40,
53
+ moneyPatterns: ['\\$\\s?\\d', '\\b(pay|paid|payment|invoice|refund|charge[ds]?|billing|bill|subscription|stripe|budget|spend|price|pricing|purchase|buy|wire|payroll|tax(es)?)\\b'],
54
+ outwardPatterns: ['\\b(send|sends|publish|post|announce|launch|ship|deploy|promote|release|merge to main|go live|email|emails|customers?|clients?|investors?|press|tweet|public)\\b'],
55
+ onlyYouPatterns: ['\\b(your|you)\\b.*\\b(approval|approve|sign|signature|password|key|token|credential|login|decision|decide|call)\\b', '\\b(approve|sign off|sign-off|need(s)? (you|him)|only (you|he) can)\\b', '\\b(api key|password|token|credentials?)\\b'],
56
+ importanceWeights: { money: 30, outward: 25, onlyYou: 25 },
45
57
  brief: { hour: 8 },
46
58
  wrap: { hour: 18 },
47
59
  selfAnswerRoutine: true,
@@ -12,6 +12,7 @@ import { unhandledAsks } from './handled-asks';
12
12
  import { renderNextSteps, renderTranscript, renderWhatHeSaid, titleFor } from './transcript';
13
13
  import { createEntityConversationStore } from './store';
14
14
  import { speakSide } from './speak';
15
+ import { ASSISTANT_NAME } from './roci';
15
16
  import { speakable } from '../briefing/speak';
16
17
  import { localDate } from '../today';
17
18
  import { toSpoken } from './spoken-form';
@@ -77,7 +78,8 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
77
78
  const n = (record?.turns.length ?? 0) + 1;
78
79
  const turnId = req.turnId ?? `t${n}-${newId()}`.slice(0, 64).replace(/[^A-Za-z0-9_-]/g, '_').padEnd(8, '_');
79
80
  const timeZone = req.timeZone || record?.timeZone || 'UTC';
80
- const hints = (record?.turns ?? []).slice(-3).map((t) => t.user.text);
81
+ // The assistant's own name leads: STT hears Rosie / Rochie / Rossi for Roci; earlier turns follow for context.
82
+ const hints = [ASSISTANT_NAME, ...(record?.turns ?? []).slice(-3).map((t) => t.user.text)];
81
83
 
82
84
  const clock = { t0: Date.now(), last: Date.now() };
83
85
  const timing: Record<string, number> = {};
@@ -85,7 +87,8 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
85
87
 
86
88
  // 1. Words.
87
89
  let utterance = req.text?.trim() ?? '';
88
- if (req.audio) {
90
+ // A recording with no bytes (the empty-file race) has nothing to transcribe: treated as silence.
91
+ if (req.audio && req.audio.audio.byteLength > 0) {
89
92
  if (!deps.transcribe) throw new ConverseError('Speech to text is not set up.', 503, 'transcription_unavailable');
90
93
  try {
91
94
  utterance = (await deps.transcribe({ audio: req.audio.audio, mimeType: req.audio.mimeType, hints })).trim();
@@ -8,6 +8,7 @@
8
8
  * and listening resumes; only a rejected session stops it.
9
9
  */
10
10
  import { ConverseClientError } from './client';
11
+ import { normalizeAssistantName } from './roci';
11
12
  import { resolveMeetingConfig, type MeetingConfig } from './meeting-config';
12
13
  import type { ConverseEndResult, ConverseIntent, ConverseSource, ConverseThread, ConverseTurnResult } from './types';
13
14
 
@@ -18,6 +19,8 @@ export interface MeetingLine {
18
19
  text: string;
19
20
  intent?: ConverseIntent;
20
21
  sources?: ConverseSource[];
22
+ /** The reply was cut off while it was being spoken (voice over it, or the Interrupt tap): the person heard only part of it. */
23
+ interrupted?: boolean;
21
24
  }
22
25
 
23
26
  export interface MeetingState {
@@ -36,6 +39,8 @@ export interface MeetingState {
36
39
  micOn: boolean;
37
40
  /** True while the microphone is actually open. With a duplex io it stays true while the reply is thought about and spoken. */
38
41
  micLive: boolean;
42
+ /** True from the moment the person's voice starts until that utterance is handed over (what the audio session calls `hearing`). */
43
+ hearing: boolean;
39
44
  }
40
45
 
41
46
  /** Why `listen` returned: the platform's detector says, the controller only needs `audio` and `cancelled`. */
@@ -106,7 +111,7 @@ export function createMeetingController<A = Blob>(options: {
106
111
  }): MeetingController {
107
112
  const { client, io } = options;
108
113
  const config = resolveMeetingConfig(options.config);
109
- let s: MeetingState = { phase: 'idle', retryable: false, lines: [], error: null, noAudio: null, conversationId: null, saved: null, relayNotice: null, micOn: false, micLive: false };
114
+ let s: MeetingState = { phase: 'idle', retryable: false, lines: [], error: null, noAudio: null, conversationId: null, saved: null, relayNotice: null, micOn: false, micLive: false, hearing: false };
110
115
  const duplex = options.io.duplex === true;
111
116
  let running = false;
112
117
  /** Wakes the loop when the mic is turned back on. */
@@ -170,6 +175,14 @@ export function createMeetingController<A = Blob>(options: {
170
175
  const startWatchdog = () => { if (!wdTimer) wdTimer = setInterval(watchdogTick, config.watchdogTickMs); };
171
176
  const stopWatchdog = () => { if (wdTimer) clearInterval(wdTimer); wdTimer = null; };
172
177
 
178
+ /** The reply being spoken was cut short: its line says so, so the transcript never shows words he did not hear. */
179
+ const markInterrupted = (): Partial<MeetingState> => {
180
+ const i = s.lines.map((l) => l.role).lastIndexOf('assistant');
181
+ const j = s.lines.map((l) => l.role).lastIndexOf('relay');
182
+ const at = Math.max(i, j);
183
+ return at < 0 ? {} : { lines: s.lines.map((l, k) => (k === at ? { ...l, interrupted: true } : l)) };
184
+ };
185
+
173
186
  async function playReply(reply: MeetingReply) {
174
187
  // A reply (a relay message, a slow answer) never talks over him: wait until his utterance is over.
175
188
  while (duplex && running && userSpeaking) await new Promise((r) => setTimeout(r, 50));
@@ -202,7 +215,7 @@ export function createMeetingController<A = Blob>(options: {
202
215
  return true;
203
216
  }
204
217
  // 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 }];
218
+ const hisWords = out.briefing && !out.transcript ? [] : [{ role: 'user' as const, text: normalizeAssistantName(out.transcript, config.assistantName) }];
206
219
  set({
207
220
  conversationId: out.conversation_id,
208
221
  lines: [...s.lines, ...hisWords, { role: 'assistant', text: out.reply_text, ...(out.intent ? { intent: out.intent } : {}), ...(out.sources?.length ? { sources: out.sources } : {}) }],
@@ -324,7 +337,9 @@ export function createMeetingController<A = Blob>(options: {
324
337
  // Barge-in: the person starts talking while the reply is being read: cut it off, what they say is the next turn.
325
338
  onSpeechStart: () => {
326
339
  userSpeaking = true;
327
- if (duplex && config.interruptOnSpeech && s.phase === 'speaking') speakAbort.abort('barge-in');
340
+ const cut = duplex && config.interruptOnSpeech && s.phase === 'speaking';
341
+ set({ hearing: true, ...(cut ? markInterrupted() : {}) });
342
+ if (cut) speakAbort.abort('barge-in');
328
343
  },
329
344
  });
330
345
  listenFailures = 0;
@@ -338,6 +353,7 @@ export function createMeetingController<A = Blob>(options: {
338
353
  continue;
339
354
  }
340
355
  userSpeaking = false;
356
+ if (s.hearing) set({ hearing: false });
341
357
  if (!running) break;
342
358
  // An io with no microphone cancels by itself: wait for End (typing still works) instead of spinning.
343
359
  if (heard.cancelled && !listenAbort.signal.aborted) {
@@ -380,6 +396,7 @@ export function createMeetingController<A = Blob>(options: {
380
396
  start() { begin(true); },
381
397
  stop() {
382
398
  stopEpoch += 1;
399
+ if (running && s.phase === 'speaking') set({ ...markInterrupted() });
383
400
  speakAbort.abort('stop');
384
401
  if (running && s.phase === 'speaking') set({ phase: restPhase() });
385
402
  },
@@ -158,7 +158,7 @@ export async function converseFleetViewResponse(deps: ConverseDeps): Promise<Res
158
158
  const snap = await loadFleetSnapshot(deps);
159
159
  const view = snap?.inputs ? buildFleetView(snap.inputs) : null;
160
160
  const state = await loadState(deps);
161
- const needs_you = buildNeedsYou({ view, decisions: state.decisions, policy: policyFrom(state.attention), answered: state.answered });
161
+ const needs_you = buildNeedsYou({ view, decisions: state.decisions, policy: policyFrom(state.attention), answered: state.answered, relay: state.relay_items });
162
162
  const body = snap
163
163
  ? { snapshot: { text: snap.text, updatedAt: snap.updatedAt, view, todoSync: parseTodoSyncRecord(snap.inputs?.todo_sync) }, needs_you }
164
164
  : { snapshot: null, needs_you };
@@ -1,13 +1,20 @@
1
1
  /**
2
2
  * THE ASSISTANT'S NAME. It is Roci. There is no wake word: nothing listens for the name. But Quinn types it the way it
3
3
  * sounds, "Rossi". Normalised on the way IN, before the model sees the text, so the assistant is never confused about
4
- * who it is being asked. ONLY "Rossi" (whole word): Rocky, Roxy and Rosie can be real names or other words, so they are
5
- * left exactly as written.
4
+ * who it is being asked. Rosie and Rocky can be real names, so they change only when plainly addressed (see below);
5
+ * Roxy and words merely containing Rossi are left exactly as written.
6
6
  */
7
7
  export const ASSISTANT_NAME = 'Roci';
8
8
 
9
- const ROSSI = /\brossi\b/gi;
9
+ /** Always Roci: "Rossi" is how it sounds typed; Rochie/Rochi/Rossie are what the transcriber writes and are not words. */
10
+ const ALWAYS = /\b(?:rossi|rossie|rochie|rochi)\b/gi;
11
+ /** Rosie and Rocky are real names: Roci only when the utterance opens with it plus a comma, or follows hey/hi/ok/okay. */
12
+ const ADDRESSED_OPENER = /^\s*(?:rosie|rocky)\s*,/i;
13
+ const AFTER_HELLO = /\b((?:hey|hi|ok|okay)[\s,]+)(?:rosie|rocky)\b/gi;
10
14
 
11
15
  export function normalizeAssistantName(text: string, name: string = ASSISTANT_NAME): string {
12
- return text ? text.replace(ROSSI, name) : text;
16
+ if (!text) return text;
17
+ let out = text.replace(ALWAYS, name).replace(AFTER_HELLO, (_m, hello: string) => hello + name);
18
+ if (ADDRESSED_OPENER.test(out)) out = out.replace(/^(\s*)(?:rosie|rocky)\b/i, (_m, lead: string) => lead + name);
19
+ return out;
13
20
  }
@@ -0,0 +1,33 @@
1
+ /** Splits a reply into chunks for speech: each ends at a sentence boundary (or, for one huge sentence, a clause or space), never mid-word. */
2
+ export const MAX_CHUNK_CHARS = 400;
3
+
4
+ const SENTENCE = /[^.!?]+(?:[.!?]+["')\]]*|$)\s*/g;
5
+
6
+ function splitLong(sentence: string, max: number): string[] {
7
+ const out: string[] = [];
8
+ let rest = sentence.trim();
9
+ while (rest.length > max) {
10
+ const window = rest.slice(0, max + 1);
11
+ let cut = Math.max(window.lastIndexOf(', '), window.lastIndexOf('; '), window.lastIndexOf(': '));
12
+ if (cut < max / 2) cut = window.lastIndexOf(' ');
13
+ if (cut <= 0) cut = max;
14
+ else if (rest[cut] === ',' || rest[cut] === ';' || rest[cut] === ':') cut += 1;
15
+ out.push(rest.slice(0, cut).trim());
16
+ rest = rest.slice(cut).trim();
17
+ }
18
+ if (rest) out.push(rest);
19
+ return out;
20
+ }
21
+
22
+ export function chunkForSpeech(text: string, max: number = MAX_CHUNK_CHARS): string[] {
23
+ const clean = text.trim();
24
+ if (clean.length <= max) return clean ? [clean] : [];
25
+ const pieces = (clean.match(SENTENCE) ?? [clean]).map((s) => s.trim()).filter(Boolean).flatMap((s) => (s.length > max ? splitLong(s, max) : [s]));
26
+ const chunks: string[] = [];
27
+ let cur = '';
28
+ for (const p of pieces) {
29
+ if (cur && cur.length + 1 + p.length > max) { chunks.push(cur); cur = p; } else cur = cur ? `${cur} ${p}` : p;
30
+ }
31
+ if (cur) chunks.push(cur);
32
+ return chunks;
33
+ }
@@ -1,7 +1,13 @@
1
1
  /** Speak a line and keep the recording, for an assistant turn and a relay message alike. Never throws: the reason is kept instead. */
2
2
  import type { ConverseDeps, ConverseSide } from './types';
3
+ import { chunkForSpeech } from './speak-chunks';
3
4
 
4
- /** `text` is kept and shown; `spoken`, when given, is what the voice says instead (a shorter version of it). */
5
+ /**
6
+ * `text` is kept and shown; `spoken`, when given, is what the voice says instead (a shorter version of it).
7
+ * A long reply is split at sentence boundaries and the chunks are synthesised TOGETHER, so the first sound waits for the slowest
8
+ * chunk and not their sum; the pieces are stitched into one recording in reading order. One chunk failing fails the whole
9
+ * reply (a half-spoken answer is worse than the text alone).
10
+ */
5
11
  export async function speakSide(deps: Pick<ConverseDeps, 'synthesize' | 'audio'>, noteId: string, text: string, spoken?: string): Promise<ConverseSide> {
6
12
  const side: ConverseSide = { text };
7
13
  if (!deps.synthesize || !deps.audio) {
@@ -9,9 +15,16 @@ export async function speakSide(deps: Pick<ConverseDeps, 'synthesize' | 'audio'>
9
15
  return side;
10
16
  }
11
17
  try {
12
- const voiced = await deps.synthesize({ text: spoken || text });
13
- side.audio_ref = await deps.audio.put({ noteId, audio: voiced.audio, mimeType: voiced.mimeType });
14
- side.audio_mime = voiced.mimeType;
18
+ const synthesize = deps.synthesize;
19
+ const parts = await Promise.all(chunkForSpeech(spoken || text).map((chunk) => synthesize({ text: chunk })));
20
+ if (!parts.length) throw new Error('nothing to say');
21
+ const mimeType = parts[0].mimeType;
22
+ const total = parts.reduce((n, p) => n + p.audio.byteLength, 0);
23
+ const audio = new Uint8Array(total);
24
+ let at = 0;
25
+ for (const p of parts) { audio.set(p.audio, at); at += p.audio.byteLength; }
26
+ side.audio_ref = await deps.audio.put({ noteId, audio, mimeType });
27
+ side.audio_mime = mimeType;
15
28
  } catch (error) {
16
29
  side.audio_reason = error instanceof Error ? error.message : String(error);
17
30
  }
@@ -5,3 +5,5 @@ export type { NotifyRequest, NotifyResult, CreateDecisionRequest } from './handl
5
5
  export * from './respond';
6
6
  export { createNotifyClient, NotifyClientError } from './client';
7
7
  export type { NotifyClient } from './client';
8
+ export { postRelayItems, relayAnswers } from './relay-items';
9
+ export type { RelayAnswer } from './relay-items';
@@ -0,0 +1,53 @@
1
+ /** The relay's own feed into the needs-you queue, and the answers read back. Request-free: a Next route and a test call these. */
2
+ import { loadState, saveState } from './state';
3
+ import { NotifyError, type NotifyDeps, type RelayItem } from './types';
4
+
5
+ const ID = /^[A-Za-z0-9_-]{3,64}$/;
6
+ const MAX_ITEMS = 100;
7
+ const clip = (s: unknown, n: number) => String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, n);
8
+
9
+ export interface RelayItemInput { id?: unknown; text?: unknown; options?: unknown; source?: unknown; link?: unknown }
10
+
11
+ /** Adds or updates questions by id (idempotent: the same post twice is the same list) and removes the ones named in `remove`. An answered id is never reopened. */
12
+ export async function postRelayItems(deps: NotifyDeps, req: { items?: unknown; remove?: unknown }) {
13
+ if (req.items !== undefined && !Array.isArray(req.items)) throw new NotifyError('items must be a list.', 400);
14
+ if (req.remove !== undefined && !Array.isArray(req.remove)) throw new NotifyError('remove must be a list of ids.', 400);
15
+ const incoming: RelayItem[] = [];
16
+ for (const raw of (req.items ?? []) as RelayItemInput[]) {
17
+ const id = String(raw?.id ?? '');
18
+ const text = clip(raw?.text, 400);
19
+ if (!ID.test(id)) throw new NotifyError('Each item needs an id of 3-64 letters, digits, - or _.', 400);
20
+ if (text.length < 3) throw new NotifyError(`Item ${id} needs a plain-language question.`, 400);
21
+ const options = Array.isArray(raw.options) ? raw.options.map((o) => clip(o, 40)).filter(Boolean).slice(0, 6) : [];
22
+ const link = clip(raw.link, 300);
23
+ const source = clip(raw.source, 60);
24
+ incoming.push({ id, text, at: new Date((deps.now ?? Date.now)()).toISOString(), ...(options.length ? { options } : {}), ...(source ? { source } : {}), ...(/^https?:\/\//.test(link) ? { link } : {}) });
25
+ }
26
+ const state = await loadState(deps);
27
+ const drop = new Set((req.remove ?? []).map(String));
28
+ let items = (state.relay_items ?? []).filter((i) => !drop.has(i.id));
29
+ for (const item of incoming) {
30
+ if (state.answered?.[`relay:${item.id}`]) continue;
31
+ const at = items.findIndex((i) => i.id === item.id);
32
+ if (at >= 0) items[at] = { ...item, at: items[at].at };
33
+ else items.push(item);
34
+ }
35
+ items = items.slice(-MAX_ITEMS);
36
+ await saveState(deps, { ...state, relay_items: items });
37
+ return { items: items.length };
38
+ }
39
+
40
+ export interface RelayAnswer { id: string; text: string; answered: boolean; answer?: string; at?: string; delivered?: boolean }
41
+
42
+ /** What the relay reads back: every question it posted, answered or not. */
43
+ export async function relayAnswers(deps: NotifyDeps): Promise<RelayAnswer[]> {
44
+ const state = await loadState(deps);
45
+ const answeredIds = Object.keys(state.answered ?? {}).filter((k) => k.startsWith('relay:')).map((k) => k.slice(6));
46
+ const known = new Map((state.relay_items ?? []).map((i) => [i.id, i]));
47
+ const ids = [...new Set([...known.keys(), ...answeredIds])];
48
+ return ids.map((id) => {
49
+ const a = state.answered?.[`relay:${id}`];
50
+ const text = known.get(id)?.text ?? '';
51
+ return a ? { id, text, answered: true, answer: a.answer, at: a.at, delivered: a.delivered === 'relay' } : { id, text, answered: false };
52
+ }).filter((r) => r.text || r.answered);
53
+ }
@@ -1,6 +1,7 @@
1
1
  /** Fetch-`Response` wrappers for the tenant frontend's route files. Each reads JSON, runs one handler, maps errors to statuses. */
2
2
  import { voiceErrorResponse } from '../voice-manage';
3
3
  import { answerDecision, createDecision, getDecision, getSettings, listDecisions, notify, registerDevice, setSettings, unregisterDevice } from './handle';
4
+ import { postRelayItems, relayAnswers } from './relay-items';
4
5
  import { NotifyError, type NotifyDeps } from './types';
5
6
 
6
7
  async function json(request: Request): Promise<Record<string, unknown>> {
@@ -41,3 +42,8 @@ export const decisionsPostResponse = (r: Request, d: NotifyDeps) => run(async ()
41
42
  export const decisionsListResponse = (status: string | null, d: NotifyDeps) => run(() => listDecisions(d, { status: status ?? undefined }));
42
43
  export const decisionGetResponse = (id: string, d: NotifyDeps) => run(() => getDecision(d, id));
43
44
  export const decisionAnswerResponse = (r: Request, id: string, d: NotifyDeps) => run(async () => { const b = await json(r); return answerDecision(d, id, { answers: b.answers, answer: b.answer }); });
45
+
46
+ /** POST /corpus/notify/relay-items {items:[{id,text,options?,source?,link?}], remove?:[id]}: the relay's questions for him (idempotent by id). */
47
+ export const relayItemsPostResponse = (r: Request, d: NotifyDeps) => run(async () => { const b = await json(r); return postRelayItems(d, { items: b.items, remove: b.remove }); });
48
+ /** GET /corpus/notify/relay-items: every question the relay posted with his answer, when there is one. */
49
+ export const relayItemsGetResponse = (d: NotifyDeps) => run(async () => ({ items: await relayAnswers(d) }));
@@ -28,6 +28,7 @@ export async function loadState(deps: Pick<NotifyDeps, 'http' | 'ownerSub'>): Pr
28
28
  ...(d.attention && typeof d.attention === 'object' ? { attention: d.attention } : {}),
29
29
  ...(d.attention_run && typeof d.attention_run === 'object' ? { attention_run: d.attention_run } : {}),
30
30
  ...(d.answered && typeof d.answered === 'object' ? { answered: d.answered } : {}),
31
+ ...(Array.isArray(d.relay_items) ? { relay_items: d.relay_items } : {}),
31
32
  };
32
33
  }
33
34
 
@@ -19,6 +19,9 @@ export interface DecisionIndexRow { id: string; title: string; status: 'pending'
19
19
  import type { AttentionRunState } from '../attention/run-steps';
20
20
  import type { StoredAttention } from '../attention/settings';
21
21
 
22
+ /** A question the relay posted for him: its own list in the notify state, separate from the fleet snapshot the sync job rewrites. */
23
+ export interface RelayItem { id: string; text: string; options?: string[]; source?: string; link?: string; at: string }
24
+
22
25
  export interface NotifyState {
23
26
  /** Default on: absent means true. */
24
27
  push_enabled: boolean;
@@ -30,7 +33,9 @@ export interface NotifyState {
30
33
  /** The needs-you briefing in progress (see ../attention/run). */
31
34
  attention_run?: AttentionRunState;
32
35
  /** Needs-you items he has answered, by item id: they leave the queue. The slice-4 delivery reads this. */
33
- answered?: Record<string, { answer: string; at: string; conversation_id: string; ref?: string; delivered?: 'decision' }>;
36
+ answered?: Record<string, { answer: string; at: string; conversation_id: string; ref?: string; delivered?: 'decision' | 'relay'; source?: 'relay'; /** The relay could not be told yet: it reads this back. */ delivery_failed?: boolean }>;
37
+ /** Questions the relay posted for him (see ./relay-items). */
38
+ relay_items?: RelayItem[];
34
39
  }
35
40
 
36
41
  export interface DecisionQuestion { n: number; text: string; options?: string[] }
@@ -56,7 +56,7 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
56
56
  );
57
57
  const { banners, services } = useMemo(() => {
58
58
  const b = createBanners();
59
- return { banners: b, services: createFoundryServices({ config, device, banners: b, strings, fakeConverse: launch.fakeConverse, fakeConverseSound: launch.fakeConverseSound, fakeBriefing: launch.fakeBriefing ? { corpus: fakeCorpus as FakeNativeCorpusApi, script: launch.fakeReply } : null }) };
59
+ return { banners: b, services: createFoundryServices({ config, device, banners: b, strings, fakeConverse: launch.fakeConverse, fakeConverseSound: launch.fakeConverseSound, voiceMock: launch.voiceMock, fakeBriefing: launch.fakeBriefing ? { corpus: fakeCorpus as FakeNativeCorpusApi, script: launch.fakeReply } : null }) };
60
60
  }, [config, device, strings, launch, fakeCorpus]);
61
61
  // The engine is the device's; a haptic that throws (no taptic hardware, simulator) never breaks a screen.
62
62
  // Every call is logged to the diagnostics (`haptic`, then `haptic.result`) so a device run proves the engine was invoked.
@@ -170,6 +170,41 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
170
170
  // `start` is only read the first time the navigator is built.
171
171
  // eslint-disable-next-line react-hooks/exhaustive-deps
172
172
  }, [tabs, saved, schema]);
173
+ // Device-test hook: `-tgVoiceAuto 1` turns the Talk mic on once the shell is up, so an audio run needs no tap.
174
+ const voiceStarted = useRef(false);
175
+ useEffect(() => {
176
+ if (!launch.voiceAuto || !nav || auth !== 'signedIn' || voiceStarted.current) return;
177
+ voiceStarted.current = true;
178
+ services.diag.log('voice.auto', { phase: services.converse?.controller.getState().phase ?? null });
179
+ services.converse?.controller.mic(true);
180
+ }, [launch, nav, auth, services]);
181
+ // Device-test hook: `-tgDevLogin 1` signs in as the local dev account on a local stack (never against *.startsimpli.com).
182
+ const devLoginTried = useRef(false);
183
+ useEffect(() => {
184
+ if (!launch.devLogin || auth !== 'signedOut' || devLoginTried.current) return;
185
+ devLoginTried.current = true;
186
+ const host = (() => { try { return new URL(config.tenant.centralUrl).hostname; } catch { return ''; } })();
187
+ if (!host || /(^|\.)startsimpli\.com$/i.test(host)) { services.diag.log('devlogin.refused', { host }); return; }
188
+ services.diag.log('devlogin', { host });
189
+ void Promise.resolve(services.session.signIn('dev@local.test', 'localdev123')).catch((e: unknown) => services.diag.log('devlogin.failed', { error: String(e) }));
190
+ }, [launch, auth, services, config]);
191
+ // Device-test hook: `-tgAudioProbe MS` writes the AVAudioSession readback (category, mode, options, route, other audio, Now Playing) to the diagnostics log.
192
+ useEffect(() => {
193
+ const session = device.recording?.session;
194
+ if (!launch.audioProbeMs || !session || auth !== 'signedIn') return undefined;
195
+ const tick = () => { void session.info().then((i) => services.diag.log('audio.info', { ...i }), (e: unknown) => services.diag.log('audio.info', { error: String(e) })); };
196
+ tick();
197
+ const t = setInterval(tick, launch.audioProbeMs);
198
+ return () => clearInterval(t);
199
+ }, [launch, device, auth, services]);
200
+ // Device-test hook: `-tgShotEvery MS` writes a JPEG of the window to Documents/shots, so a wireless run still has screenshots.
201
+ useEffect(() => {
202
+ const snap = device.recording?.session.snapshot;
203
+ if (!launch.shotEveryMs || !snap || auth !== 'signedIn') return undefined;
204
+ const shoot = () => { void snap(device.documentUri(`shots/${Date.now()}.jpg`)).catch(() => false); };
205
+ const t = setInterval(shoot, launch.shotEveryMs);
206
+ return () => clearInterval(t);
207
+ }, [launch, device, auth]);
173
208
  useEffect(() => {
174
209
  if (!nav) return undefined;
175
210
  services.bindOpen((tab, id) => nav.open(tab, id ? { id } : null));
@@ -90,3 +90,29 @@ describe('briefing services', () => {
90
90
  expect(notifier.schedule).not.toHaveBeenCalled();
91
91
  });
92
92
  });
93
+
94
+ describe('lock-screen Now Playing for the briefing', () => {
95
+ const nowPlaying = () => {
96
+ const cbs = new Set<(c: 'play' | 'pause' | 'stop') => void>();
97
+ return { set: vi.fn(), clear: vi.fn(), onCommand: (cb: (c: 'play' | 'pause' | 'stop') => void) => { cbs.add(cb); return () => { cbs.delete(cb); }; }, fire: (c: 'play' | 'pause' | 'stop') => cbs.forEach((cb) => cb(c)) };
98
+ };
99
+ const dev = (np: ReturnType<typeof nowPlaying>) => {
100
+ const base = device() as any;
101
+ return { ...base, briefing: { ...base.briefing, nowPlaying: np } } as never;
102
+ };
103
+ it('test_briefing_playback_registers_now_playing_and_the_stop_command_ends_it', async () => {
104
+ const np = nowPlaying();
105
+ const { services } = make({ briefing: true }, dev(np));
106
+ await services.briefing!.player.play({ uri: 'fixture://briefing' });
107
+ expect(np.set).toHaveBeenCalled();
108
+ expect(np.set.mock.calls.at(-1)![0]).toMatchObject({ rate: 1, durationMs: 1000 });
109
+ np.fire('stop');
110
+ await new Promise((r) => setTimeout(r, 0)); // stop() releases the driver asynchronously
111
+ expect(services.briefing!.player.getState().phase).toBe('idle');
112
+ expect(np.clear).toHaveBeenCalled();
113
+ });
114
+ it('test_without_a_now_playing_binding_nothing_is_registered', async () => {
115
+ const { services } = make({ briefing: true });
116
+ await expect(services.briefing!.player.play({ uri: 'fixture://briefing' })).resolves.toBeUndefined();
117
+ });
118
+ });