@startsimpli/integrations 0.2.223 → 0.2.225

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 (65) hide show
  1. package/package.json +5 -5
  2. package/src/__tests__/attention-importance.test.ts +51 -0
  3. package/src/__tests__/attention-policy.test.ts +174 -0
  4. package/src/__tests__/attention-rhythm.test.ts +95 -0
  5. package/src/__tests__/attention-run.test.ts +132 -0
  6. package/src/__tests__/attention-settings-page.test.tsx +57 -0
  7. package/src/__tests__/attention-settings.test.ts +86 -0
  8. package/src/__tests__/converse-client.test.ts +6 -0
  9. package/src/__tests__/converse-meeting.test.ts +40 -0
  10. package/src/__tests__/converse-relay.test.ts +35 -0
  11. package/src/__tests__/converse-roci.test.ts +16 -1
  12. package/src/__tests__/converse-soak.test.ts +61 -0
  13. package/src/__tests__/converse-watchdog.test.ts +107 -0
  14. package/src/__tests__/decisions-page.test.tsx +1 -1
  15. package/src/__tests__/fleet-view.test.ts +1 -1
  16. package/src/__tests__/relay-items.test.ts +89 -0
  17. package/src/components/index.ts +1 -0
  18. package/src/components/pages/AttentionSettings.tsx +51 -0
  19. package/src/components/pages/DecisionsPage.tsx +13 -2
  20. package/src/corpus/attention/controller.ts +37 -0
  21. package/src/corpus/attention/importance.ts +17 -0
  22. package/src/corpus/attention/index.ts +9 -0
  23. package/src/corpus/attention/policy.ts +61 -0
  24. package/src/corpus/attention/push.ts +47 -0
  25. package/src/corpus/attention/queue.ts +26 -0
  26. package/src/corpus/attention/rhythm.ts +69 -0
  27. package/src/corpus/attention/run-steps.ts +90 -0
  28. package/src/corpus/attention/run.ts +65 -0
  29. package/src/corpus/attention/settings.ts +80 -0
  30. package/src/corpus/attention/types.ts +75 -0
  31. package/src/corpus/converse/client.ts +3 -2
  32. package/src/corpus/converse/handle.ts +18 -3
  33. package/src/corpus/converse/meeting-config.ts +15 -1
  34. package/src/corpus/converse/meeting.ts +100 -8
  35. package/src/corpus/converse/respond.ts +12 -2
  36. package/src/corpus/converse/roci.ts +11 -4
  37. package/src/corpus/converse/types.ts +11 -0
  38. package/src/corpus/index.ts +1 -0
  39. package/src/corpus/notify/client.ts +10 -2
  40. package/src/corpus/notify/handle.ts +9 -5
  41. package/src/corpus/notify/index.ts +2 -0
  42. package/src/corpus/notify/relay-items.ts +53 -0
  43. package/src/corpus/notify/respond.ts +7 -1
  44. package/src/corpus/notify/state.ts +4 -0
  45. package/src/corpus/notify/types.ts +14 -0
  46. package/src/native/app/converseServices.ts +1 -0
  47. package/src/native/app/notifyServices.ts +8 -1
  48. package/src/native/app/registry.tsx +4 -2
  49. package/src/native/app/services.ts +1 -1
  50. package/src/native/converse/DriveScreen.tsx +47 -0
  51. package/src/native/converse/__tests__/driveScreen.test.tsx +54 -0
  52. package/src/native/converse/api.ts +1 -0
  53. package/src/native/converse/fake.ts +4 -0
  54. package/src/native/converse/index.ts +1 -0
  55. package/src/native/converse/io.ts +1 -0
  56. package/src/native/push/AttentionCard.tsx +44 -0
  57. package/src/native/push/DecisionsScreen.tsx +12 -2
  58. package/src/native/push/NeedsYouCard.tsx +42 -0
  59. package/src/native/push/__tests__/decisionsApp.test.tsx +12 -1
  60. package/src/native/push/__tests__/needsYou.test.tsx +106 -0
  61. package/src/native/push/fake.ts +12 -1
  62. package/src/native/push/index.ts +3 -0
  63. package/src/native/push/needsYou.ts +29 -0
  64. package/src/native/push/tab.tsx +4 -2
  65. package/src/native/talk/TalkTab.tsx +24 -2
@@ -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
  }
@@ -4,6 +4,8 @@
4
4
  * POST /corpus/converse/end JSON {conversation_id}
5
5
  * GET /corpus/converse/<id>/turn/<n>/audio[?who=user] a turn's recording, to its owner only
6
6
  */
7
+ import { buildNeedsYou, policyFrom } from '../attention';
8
+ import { loadState } from '../notify/state';
7
9
  import { parseTodoSyncRecord } from './sync-health';
8
10
  import { isTimeZone } from '../spoken-time';
9
11
  import { voiceErrorResponse } from '../voice-manage';
@@ -53,6 +55,7 @@ export async function converseResponse(request: Request, deps: ConverseDeps): Pr
53
55
  conversationId: str(fields.conversation_id ?? fields.conversationId),
54
56
  turnId: str(fields.turn_id ?? fields.turnId),
55
57
  ...(str(fields.text) ? { text: str(fields.text) } : {}),
58
+ ...(str(fields.briefing) === 'start' ? { briefing: 'start' as const } : {}),
56
59
  ...(audio ? { audio } : {}),
57
60
  ...(zone && isTimeZone(zone) ? { timeZone: zone } : {}),
58
61
  }));
@@ -140,7 +143,9 @@ export async function converseThreadResponse(conversationId: string, after: stri
140
143
  export async function converseFleetStatusResponse(request: Request, deps: ConverseDeps): Promise<Response> {
141
144
  try {
142
145
  const { fields } = await fieldsOf(request);
143
- const saved = await saveFleetSnapshot(deps, typeof fields.text === 'string' ? fields.text : '', cleanFleetInputs(fields.inputs));
146
+ const inputs = cleanFleetInputs(fields.inputs);
147
+ const saved = await saveFleetSnapshot(deps, typeof fields.text === 'string' ? fields.text : '', inputs);
148
+ await deps.onFleetSnapshot?.({ view: inputs ? buildFleetView(inputs) : null }).catch((e) => console.error('[converse] fleet attention failed', e));
144
149
  return Response.json({ saved: true, record_id: saved.record_id, updated_at: saved.updatedAt });
145
150
  } catch (error) {
146
151
  return failure(error);
@@ -151,7 +156,12 @@ export async function converseFleetStatusResponse(request: Request, deps: Conver
151
156
  export async function converseFleetViewResponse(deps: ConverseDeps): Promise<Response> {
152
157
  try {
153
158
  const snap = await loadFleetSnapshot(deps);
154
- const body = snap ? { snapshot: { text: snap.text, updatedAt: snap.updatedAt, view: snap.inputs ? buildFleetView(snap.inputs) : null, todoSync: parseTodoSyncRecord(snap.inputs?.todo_sync) } } : { snapshot: null };
159
+ const view = snap?.inputs ? buildFleetView(snap.inputs) : null;
160
+ const state = await loadState(deps);
161
+ const needs_you = buildNeedsYou({ view, decisions: state.decisions, policy: policyFrom(state.attention), answered: state.answered, relay: state.relay_items });
162
+ const body = snap
163
+ ? { snapshot: { text: snap.text, updatedAt: snap.updatedAt, view, todoSync: parseTodoSyncRecord(snap.inputs?.todo_sync) }, needs_you }
164
+ : { snapshot: null, needs_you };
155
165
  return Response.json(body, { headers: { 'cache-control': 'no-store' } });
156
166
  } catch (error) {
157
167
  return failure(error);
@@ -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
  }
@@ -38,6 +38,8 @@ export interface ConverseTurn {
38
38
  intent?: ConverseIntent;
39
39
  /** The records an answer came from (documents, items, projects), for the thread to show. */
40
40
  sources?: ConverseSource[];
41
+ /** Set on a needs-you briefing turn. */
42
+ attn?: { active: boolean; index: number; of: number };
41
43
  }
42
44
 
43
45
  /** note: a plan or thoughts to keep; question: asked and answered; command: a change to his to-dos; relay: for the relay; briefing: the one-item-at-a-time walk; chat: small talk. */
@@ -79,6 +81,7 @@ export interface ConversationStore {
79
81
  /** What the assistant works out for one utterance. */
80
82
  import type { BriefingState } from './briefing-queue';
81
83
  import type { PlayedItem } from './followups';
84
+ import type { FleetView } from './fleet-view';
82
85
 
83
86
  /** The instruction that could not be placed and the question asked back: the next turn reads both together. */
84
87
  export interface PendingClarify { utterance: string; question: string }
@@ -131,6 +134,8 @@ export interface ConverseTurnRequest {
131
134
  timeZone?: string;
132
135
  /** Fresh per press; optional. */
133
136
  turnId?: string;
137
+ /** `start`: the assistant begins the needs-you briefing itself (no words from the person). */
138
+ briefing?: 'start';
134
139
  }
135
140
 
136
141
  /** The 200 body. */
@@ -149,6 +154,8 @@ export interface ConverseTurnResult {
149
154
  /** True when this turn wrapped the conversation up and filed it; the next message starts a new conversation. */
150
155
  ended?: boolean;
151
156
  filed?: { note: boolean; todos: number };
157
+ /** Present on a needs-you briefing turn: where the walk is. `active` false means it just finished. */
158
+ briefing?: { active: boolean; index: number; of: number };
152
159
  }
153
160
 
154
161
  /** One line of a thread as the page and the relay read it. `who` is whose words `reply_text`/`transcript` are. */
@@ -215,6 +222,10 @@ export interface ConverseDeps {
215
222
  onTiming?: (timing: Record<string, number>, info: { conversationId: string; turn: number }) => void;
216
223
  /** Called when the relay answers a conversation the person has already ended, so they can be told (a push). Errors are ignored. */
217
224
  onRelayReplyAfterEnd?: (info: { conversationId: string; text: string }) => Promise<void>;
225
+ /** Called after a fleet snapshot has been saved (attention pushes hang off this). Errors are ignored: the snapshot is already saved. */
226
+ /** The needs-you briefing (see ../attention/run). Absent: briefing turns are refused as empty. */
227
+ attentionRun?: import('../attention/run').AttentionRunApi;
228
+ onFleetSnapshot?: (info: { view: FleetView | null }) => Promise<void>;
218
229
  }
219
230
 
220
231
  /** An error the route turns into a status; `code` lets the app choose its message. */
@@ -293,6 +293,7 @@ export type { TodayEntry, TodayItem, TodayKind, TodayRule } from './today';
293
293
  export * from './briefing';
294
294
  export * from './converse';
295
295
  export * from './notify';
296
+ export * from './attention';
296
297
 
297
298
  // Spoken time -> due dates, and the per-field guesses extraction reports (bd startsim-b7kir).
298
299
  export { isTimeZone, noteWideWhen, resolveSpokenTime } from './spoken-time';
@@ -1,4 +1,6 @@
1
1
  /** The browser/phone side of decisions and the push setting: the bearer goes on every call. No React, so web and native share it. */
2
+ import type { AttentionSettings, StoredAttention } from '../attention/settings';
3
+ import type { NeedsYouQueue } from '../attention/types';
2
4
  import type { DecisionIndexRow, DecisionRecord } from './types';
3
5
 
4
6
  export class NotifyClientError extends Error {
@@ -9,8 +11,12 @@ export interface NotifyClient {
9
11
  pending(): Promise<DecisionIndexRow[]>;
10
12
  decision(id: string): Promise<DecisionRecord>;
11
13
  answer(id: string, answers: Array<{ n: number; answer: string }>): Promise<DecisionRecord>;
12
- settings(): Promise<{ push: boolean; devices: number }>;
13
- setPush(push: boolean): Promise<{ push: boolean; devices: number }>;
14
+ settings(): Promise<{ push: boolean; devices: number; attention?: AttentionSettings }>;
15
+ setPush(push: boolean): Promise<{ push: boolean; devices: number; attention?: AttentionSettings }>;
16
+ /** Quiet mode, schedule, urgent words, call-me threshold: send only what changed. */
17
+ setAttention(patch: StoredAttention): Promise<AttentionSettings>;
18
+ /** What needs the person now (urgent and waiting items from the fleet snapshot and his pending decisions). */
19
+ needsYou(): Promise<NeedsYouQueue>;
14
20
  }
15
21
 
16
22
  export function createNotifyClient(options: { getToken: () => Promise<string | null | undefined>; base?: string; fetch?: typeof fetch }): NotifyClient {
@@ -36,5 +42,7 @@ export function createNotifyClient(options: { getToken: () => Promise<string | n
36
42
  answer: (id, answers) => call('POST', `/decisions/${encodeURIComponent(id)}/answer`, { answers }),
37
43
  settings: () => call('GET', '/notify/settings'),
38
44
  setPush: (push) => call('PUT', '/notify/settings', { push }),
45
+ setAttention: async (patch) => (await call<{ attention: AttentionSettings }>('PUT', '/notify/settings', { attention: patch })).attention,
46
+ needsYou: async () => (await call<{ needs_you: NeedsYouQueue }>('GET', '/converse/fleet-status')).needs_you,
39
47
  };
40
48
  }
@@ -1,4 +1,5 @@
1
1
  /** Devices, the push setting, notify, and decisions. Request-free: a Next route and a test call the same functions. */
2
+ import { mergeAttention, settingsView } from '../attention/settings';
2
3
  import { loadDecision, loadState, saveDecision, saveState } from './state';
3
4
  import {
4
5
  MAX_DEVICES, MAX_PINGS, NOTIFY_ID, NotifyError,
@@ -30,14 +31,17 @@ export async function unregisterDevice(deps: NotifyDeps, req: { token?: string }
30
31
 
31
32
  export async function getSettings(deps: NotifyDeps) {
32
33
  const s = await loadState(deps);
33
- return { push: s.push_enabled, devices: s.devices.length };
34
+ return { push: s.push_enabled, devices: s.devices.length, attention: settingsView(s.attention, (deps.now ?? Date.now)()) };
34
35
  }
35
36
 
36
- export async function setSettings(deps: NotifyDeps, req: { push?: unknown }) {
37
- if (typeof req.push !== 'boolean') throw new NotifyError('push must be true or false.', 400);
37
+ export async function setSettings(deps: NotifyDeps, req: { push?: unknown; attention?: unknown }) {
38
+ if (req.push === undefined && req.attention === undefined) throw new NotifyError('push must be true or false.', 400);
39
+ if (req.push !== undefined && typeof req.push !== 'boolean') throw new NotifyError('push must be true or false.', 400);
38
40
  const s = await loadState(deps);
39
- if (s.push_enabled !== req.push) await saveState(deps, { ...s, push_enabled: req.push });
40
- return { push: req.push, devices: s.devices.length };
41
+ const attention = req.attention === undefined ? s.attention : mergeAttention(s.attention, req.attention);
42
+ const push = req.push === undefined ? s.push_enabled : req.push;
43
+ if (s.push_enabled !== push || attention !== s.attention) await saveState(deps, { ...s, push_enabled: push, ...(attention ? { attention } : {}) });
44
+ return { push, devices: s.devices.length, attention: settingsView(attention, (deps.now ?? Date.now)()) };
41
45
  }
42
46
 
43
47
  export interface NotifyRequest { kind?: string; title?: string; body?: string; thread_id?: string; decision_id?: string; priority?: string; ping_id?: string }
@@ -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>> {
@@ -28,7 +29,7 @@ async function run(work: () => Promise<unknown>, status = 200): Promise<Response
28
29
  export const devicesPostResponse = (r: Request, d: NotifyDeps) => run(async () => { const b = await json(r); return registerDevice(d, { token: str(b.token), environment: str(b.environment), platform: str(b.platform), label: str(b.label) }); });
29
30
  export const devicesDeleteResponse = (r: Request, d: NotifyDeps) => run(async () => unregisterDevice(d, { token: str((await json(r)).token) }));
30
31
  export const settingsGetResponse = (d: NotifyDeps) => run(() => getSettings(d));
31
- export const settingsPutResponse = (r: Request, d: NotifyDeps) => run(async () => setSettings(d, { push: (await json(r)).push }));
32
+ export const settingsPutResponse = (r: Request, d: NotifyDeps) => run(async () => { const b = await json(r); return setSettings(d, { push: b.push, attention: b.attention }); });
32
33
  export const notifyResponse = (r: Request, d: NotifyDeps) => run(async () => {
33
34
  const b = await json(r);
34
35
  return notify(d, { kind: str(b.kind), title: str(b.title), body: str(b.body), thread_id: str(b.thread_id), decision_id: str(b.decision_id), priority: str(b.priority), ping_id: str(b.ping_id) });
@@ -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) }));
@@ -25,6 +25,10 @@ export async function loadState(deps: Pick<NotifyDeps, 'http' | 'ownerSub'>): Pr
25
25
  devices: Array.isArray(d.devices) ? d.devices : [],
26
26
  pings: Array.isArray(d.pings) ? d.pings : [],
27
27
  decisions: Array.isArray(d.decisions) ? d.decisions : [],
28
+ ...(d.attention && typeof d.attention === 'object' ? { attention: d.attention } : {}),
29
+ ...(d.attention_run && typeof d.attention_run === 'object' ? { attention_run: d.attention_run } : {}),
30
+ ...(d.answered && typeof d.answered === 'object' ? { answered: d.answered } : {}),
31
+ ...(Array.isArray(d.relay_items) ? { relay_items: d.relay_items } : {}),
28
32
  };
29
33
  }
30
34
 
@@ -16,12 +16,26 @@ export interface DeviceRecord { token: string; environment: PushEnvironment; pla
16
16
  export interface PingRecord { id: string; at: string; kind: NotifyKind; title: string; body: string; thread_id?: string; decision_id?: string; priority: NotifyPriority; delivered: number }
17
17
  export interface DecisionIndexRow { id: string; title: string; status: 'pending' | 'answered'; created_at: string }
18
18
 
19
+ import type { AttentionRunState } from '../attention/run-steps';
20
+ import type { StoredAttention } from '../attention/settings';
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
+
19
25
  export interface NotifyState {
20
26
  /** Default on: absent means true. */
21
27
  push_enabled: boolean;
22
28
  devices: DeviceRecord[];
23
29
  pings: PingRecord[];
24
30
  decisions: DecisionIndexRow[];
31
+ /** Quiet mode, urgent words and thresholds the person set (see ../attention/settings). */
32
+ attention?: StoredAttention;
33
+ /** The needs-you briefing in progress (see ../attention/run). */
34
+ attention_run?: AttentionRunState;
35
+ /** Needs-you items he has answered, by item id: they leave the queue. The slice-4 delivery reads this. */
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[];
25
39
  }
26
40
 
27
41
  export interface DecisionQuestion { n: number; text: string; options?: string[] }
@@ -64,6 +64,7 @@ export function createConverse(deps: {
64
64
  const io = fakes ? (fakeSound ? { listen: fakes.io.listen, speak: real.speak } : fakes.io) : real;
65
65
  const controller = createMeetingController({
66
66
  client: api, io, config: deps.meeting,
67
+ onHeal: (event, fields) => diag.log(`meeting.healed.${event}`, fields),
67
68
  onChange: (s) => diag.log('meeting.state', { phase: s.phase, micLive: s.micLive, error: s.error, noAudio: s.noAudio }),
68
69
  });
69
70
  return { controller, player, speed };
@@ -2,6 +2,8 @@ import { createNotifyClient } from '../../corpus/notify';
2
2
  import { createDecisionsController } from '../push/decisions';
3
3
  import { createPushController } from '../push/controller';
4
4
  import { createFakeNotify } from '../push/fake';
5
+ import { createAttentionController } from '../../corpus/attention/controller';
6
+ import { createNeedsYouController } from '../push/needsYou';
5
7
  import { createPushRegistry } from '../push/registry';
6
8
  import type { PushTap } from '../push/types';
7
9
  import type { createDiagnostics } from '../recording/diagnostics';
@@ -30,20 +32,25 @@ export function createNotify(deps: {
30
32
  : createPushRegistry({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch });
31
33
  const push = createPushController({ client, registry, device: device.push ?? null, diag });
32
34
  const decisions = createDecisionsController({ client });
35
+ const needsYou = createNeedsYouController({ client });
36
+ const attention = createAttentionController({ client });
33
37
 
34
38
  const tabKey = (screen: string) => config.tabs.find((t) => t.screen === screen)?.key;
35
39
  const route = (tap: PushTap) => {
36
40
  diag.log('push.tap', { kind: tap.kind, decision: tap.decision_id, thread: tap.thread_id });
37
41
  const decisionsKey = tabKey('decisions');
38
42
  const converseKey = tabKey('converse');
43
+ const talkKey = tabKey('talk');
39
44
  if (tap.decision_id && decisionsKey) deps.handleLink(`${config.app.scheme}://tab/${decisionsKey}/${encodeURIComponent(tap.decision_id)}`);
45
+ // An urgent / call-me push opens Talk, which loads the needs-you queue as it comes on screen.
46
+ else if (tap.kind === 'attention' && talkKey) { needsYou.requestBriefing(); void needsYou.refresh(); deps.handleLink(`${config.app.scheme}://tab/${talkKey}`); }
40
47
  else if (converseKey) deps.handleLink(`${config.app.scheme}://tab/${converseKey}`);
41
48
  else if (decisionsKey) deps.handleLink(`${config.app.scheme}://tab/${decisionsKey}`);
42
49
  };
43
50
  const unsubscribeTaps = device.push?.onTap(route);
44
51
 
45
52
  return {
46
- push, decisions,
53
+ push, decisions, needsYou, attention,
47
54
  /** After sign-in: read the setting, register this phone, and open what a push launched the app from. */
48
55
  async onReady() {
49
56
  await push.sync();