@startsimpli/integrations 0.2.200 → 0.2.201

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 (70) hide show
  1. package/package.json +6 -6
  2. package/src/__tests__/briefing-actions.test.ts +11 -0
  3. package/src/__tests__/briefing-edits.test.ts +98 -0
  4. package/src/__tests__/converse-brain.test.ts +64 -1
  5. package/src/__tests__/converse-handoff.test.ts +8 -0
  6. package/src/__tests__/converse-meeting-brief.test.ts +72 -8
  7. package/src/__tests__/converse-meeting-duplex.test.ts +132 -0
  8. package/src/__tests__/converse-meeting-keep-speech.test.ts +87 -0
  9. package/src/__tests__/converse-meeting-vad.test.ts +1 -1
  10. package/src/__tests__/converse-spoken-form.test.ts +10 -0
  11. package/src/__tests__/converse-spoken-summary.test.ts +27 -6
  12. package/src/__tests__/converse.test.ts +29 -2
  13. package/src/__tests__/corpus-ask.test.ts +22 -0
  14. package/src/__tests__/corpus-tracker.test.tsx +12 -0
  15. package/src/__tests__/extract-classify.test.ts +17 -0
  16. package/src/__tests__/fleet-page.test.tsx +57 -0
  17. package/src/__tests__/fleet-view.test.ts +149 -0
  18. package/src/__tests__/project-basis-entity.test.ts +19 -0
  19. package/src/__tests__/project-basis.test.ts +21 -0
  20. package/src/__tests__/relay-cli.test.ts +10 -1
  21. package/src/__tests__/task-detail-project-guess.test.tsx +46 -0
  22. package/src/components/index.ts +2 -0
  23. package/src/components/pages/FleetPage.tsx +115 -0
  24. package/src/components/pages/TaskDetailPage.tsx +27 -1
  25. package/src/components/pages/TrackerPage.tsx +1 -1
  26. package/src/components/pages/task-tracker/ProjectGuess.tsx +42 -0
  27. package/src/corpus/ask-items.ts +7 -4
  28. package/src/corpus/ask.ts +1 -1
  29. package/src/corpus/briefing/actions/confirm.ts +9 -1
  30. package/src/corpus/briefing/actions/execute.ts +71 -11
  31. package/src/corpus/briefing/actions/log.ts +1 -1
  32. package/src/corpus/briefing/actions/seam.ts +18 -2
  33. package/src/corpus/briefing/actions/types.ts +14 -0
  34. package/src/corpus/briefing/intent/describe.ts +5 -1
  35. package/src/corpus/briefing/intent/edits.ts +92 -0
  36. package/src/corpus/briefing/intent/grammar.ts +3 -0
  37. package/src/corpus/briefing/intent/ground.ts +5 -1
  38. package/src/corpus/briefing/intent/match.ts +3 -1
  39. package/src/corpus/briefing/intent/model.ts +36 -3
  40. package/src/corpus/briefing/intent/resolve.ts +12 -1
  41. package/src/corpus/briefing/intent/types.ts +8 -0
  42. package/src/corpus/briefing/speak.ts +13 -0
  43. package/src/corpus/client.ts +2 -0
  44. package/src/corpus/converse/brain.ts +41 -13
  45. package/src/corpus/converse/briefing-queue.ts +105 -27
  46. package/src/corpus/converse/client.ts +6 -0
  47. package/src/corpus/converse/fleet-view.ts +126 -0
  48. package/src/corpus/converse/fleet.ts +18 -5
  49. package/src/corpus/converse/followups.ts +12 -2
  50. package/src/corpus/converse/handle.ts +21 -12
  51. package/src/corpus/converse/handoff.ts +7 -2
  52. package/src/corpus/converse/index.ts +5 -3
  53. package/src/corpus/converse/meeting-config.ts +8 -4
  54. package/src/corpus/converse/meeting.ts +66 -11
  55. package/src/corpus/converse/respond.ts +14 -2
  56. package/src/corpus/converse/spoken-form.ts +9 -2
  57. package/src/corpus/converse/spoken-summary.ts +30 -8
  58. package/src/corpus/converse/store.ts +2 -0
  59. package/src/corpus/converse/types.ts +14 -1
  60. package/src/corpus/entities.ts +2 -0
  61. package/src/corpus/extract.ts +9 -4
  62. package/src/corpus/project-basis.ts +23 -0
  63. package/src/corpus/types.ts +6 -0
  64. package/src/native/app/converseServices.ts +5 -3
  65. package/src/native/app/device.ts +2 -0
  66. package/src/native/converse/ConverseScreen.tsx +28 -0
  67. package/src/native/converse/__tests__/liveScreen.test.tsx +35 -2
  68. package/src/native/converse/__tests__/meetingIO.test.ts +55 -1
  69. package/src/native/converse/format.ts +2 -2
  70. package/src/native/converse/io.ts +15 -5
@@ -5,14 +5,27 @@
5
5
  */
6
6
  import type { TenantEntity } from '../entities';
7
7
  import { ConverseError, type ConverseDeps } from './types';
8
+ import type { FleetInputs } from './fleet-view';
8
9
 
9
10
  export const FLEET_SOURCE = 'fleet_status';
10
11
  export const MAX_FLEET_TEXT = 20000;
11
12
  export const fleetExternalId = (ownerSub: string) => `fleet-status:${ownerSub}`;
12
13
 
13
- export interface FleetSnapshot { text: string; updatedAt: string }
14
+ export const MAX_FLEET_INPUT = 200000;
15
+ export interface FleetSnapshot { text: string; updatedAt: string; inputs?: FleetInputs }
14
16
 
15
- export async function saveFleetSnapshot(deps: Pick<ConverseDeps, 'http' | 'ownerSub' | 'now'>, text: string): Promise<FleetSnapshot & { record_id: string }> {
17
+ /** Only the three known raw inputs, as capped strings. */
18
+ export function cleanFleetInputs(raw: unknown): FleetInputs | undefined {
19
+ if (!raw || typeof raw !== 'object') return undefined;
20
+ const out: FleetInputs = {};
21
+ for (const k of ['roles', 'loops', 'sessions', 'ports'] as const) {
22
+ const v = (raw as Record<string, unknown>)[k];
23
+ if (typeof v === 'string' && v.trim()) out[k] = v.slice(0, MAX_FLEET_INPUT);
24
+ }
25
+ return Object.keys(out).length ? out : undefined;
26
+ }
27
+
28
+ export async function saveFleetSnapshot(deps: Pick<ConverseDeps, 'http' | 'ownerSub' | 'now'>, text: string, inputs?: FleetInputs): Promise<FleetSnapshot & { record_id: string }> {
16
29
  const body = (text ?? '').trim();
17
30
  if (!body) throw new ConverseError('Send the snapshot text.', 400);
18
31
  if (body.length > MAX_FLEET_TEXT) throw new ConverseError('That snapshot is too long.', 413);
@@ -23,10 +36,10 @@ export async function saveFleetSnapshot(deps: Pick<ConverseDeps, 'http' | 'owner
23
36
  name: 'Fleet status',
24
37
  data: {
25
38
  title: 'Fleet status', source: FLEET_SOURCE, source_label: 'Fleet status', source_ref: fleetExternalId(deps.ownerSub),
26
- occurred_at: updatedAt, owner_sub: deps.ownerSub, body, updated_at: updatedAt,
39
+ occurred_at: updatedAt, owner_sub: deps.ownerSub, body, updated_at: updatedAt, ...(inputs ? { fleet_inputs: inputs } : {}),
27
40
  },
28
41
  });
29
- return { text: body, updatedAt, record_id: String(row.id) };
42
+ return { text: body, updatedAt, inputs, record_id: String(row.id) };
30
43
  }
31
44
 
32
45
  export async function loadFleetSnapshot(deps: Pick<ConverseDeps, 'http' | 'ownerSub'>): Promise<FleetSnapshot | null> {
@@ -39,7 +52,7 @@ export async function loadFleetSnapshot(deps: Pick<ConverseDeps, 'http' | 'owner
39
52
  return (r.external_id ?? r.externalId) === externalId && d.owner_sub === deps.ownerSub && d.source === FLEET_SOURCE;
40
53
  });
41
54
  const d = (hit?.data ?? {}) as Record<string, unknown>;
42
- return hit && typeof d.body === 'string' && d.body ? { text: d.body, updatedAt: typeof d.updated_at === 'string' ? d.updated_at : '' } : null;
55
+ return hit && typeof d.body === 'string' && d.body ? { text: d.body, updatedAt: typeof d.updated_at === 'string' ? d.updated_at : '', inputs: cleanFleetInputs(d.fleet_inputs) } : null;
43
56
  }
44
57
 
45
58
  /** "3 hours ago" for a timestamp; '' when it cannot be read. Said aloud, so words not numbers-with-units. */
@@ -18,14 +18,17 @@ export type FollowUp =
18
18
  | { kind: 'ask'; text: string };
19
19
 
20
20
  const ORDINALS: Record<string, number> = { first: 0, '1st': 0, one: 0, second: 1, '2nd': 1, two: 1, third: 2, '3rd': 2, three: 2, fourth: 3, '4th': 3, four: 3 };
21
- const EDIT = /^(?:(?:please|can you|could you)\s+)?(move|push|defer|bump|reschedule|schedule|mark|set|make|complete|finish|drop|delete|remove|cancel|do|put|pull|snooze)\b/i;
21
+ const EDIT = /^(?:(?:please|can you|could you)\s+)?(move|push|defer|bump|reschedule|schedule|mark|set|make|complete|finish|drop|delete|remove|cancel|do|put|pull|snooze|rename|retitle|file|add\s+(?:a\s+)?note)\b/i;
22
22
  const DETAIL = /^(?:tell me more (?:about|on)|more (?:about|on)|details? (?:on|about|of)|what about|how about|when is|when's)\b/i;
23
23
  const ORDINAL_REF = /\b(?:the\s+)?(first|second|third|fourth|last)(?:\s+one)?\b|\bnumber\s+(one|two|three|four)\b/i;
24
+ /** "all of those", "both of them", "every one": the whole list. */
25
+ const ALL_REF = /\b(?:all|both|every one|each one)(?:\s+of)?\s+(?:those|them|these|the (?:items|ones|to-?dos|tasks))\b|\b(?:them|those) all\b/i;
26
+ const MAX_BULK = 8;
24
27
  const THAT_ONE = /\b(?:that|this)\s+one\b/i;
25
28
  const BARE_IT = /\b(?:it|that)\b/i;
26
29
 
27
30
  /** Cheap check before reading anything: could this line be a follow-up about an item just listed? */
28
- export const mightFollowUp = (utterance: string): boolean => (EDIT.test(utterance.trim()) || DETAIL.test(utterance.trim())) && (ORDINAL_REF.test(utterance) || THAT_ONE.test(utterance) || BARE_IT.test(utterance));
31
+ export const mightFollowUp = (utterance: string): boolean => (EDIT.test(utterance.trim()) || DETAIL.test(utterance.trim())) && (ORDINAL_REF.test(utterance) || THAT_ONE.test(utterance) || BARE_IT.test(utterance) || ALL_REF.test(utterance));
29
32
 
30
33
  const quote = (title: string) => `"${title}"`;
31
34
 
@@ -46,6 +49,13 @@ export function followUp(input: { utterance: string; items: PlayedItem[]; rows:
46
49
  const detail = DETAIL.test(said);
47
50
  if (!edit && !detail) return null;
48
51
 
52
+ // The whole list: the same instruction once per item, as one sentence the edit path splits again ("mark A done and mark B done").
53
+ const all = ALL_REF.exec(said);
54
+ if (all && edit && items.length > 1) {
55
+ const each = items.slice(0, MAX_BULK).map((i) => said.replace(all[0], quote(i.title)).replace(/\s+/g, ' ').trim());
56
+ return { kind: 'rewrite', utterance: each.join(' and ') };
57
+ }
58
+
49
59
  // Which item, and the words that named it.
50
60
  let index: number | null = null;
51
61
  let span: string | null = null;
@@ -22,13 +22,14 @@ import {
22
22
  } from './types';
23
23
 
24
24
  const DEFAULT_HISTORY_LINES = 24;
25
- /** What is said after wrapping up: what was filed, in one short sentence. */
26
- function filedText(asks: string[]): string {
27
- if (!asks.length) return 'Filed the note.';
28
- const titles = asks.slice(0, 3).map((a) => speakable(a, 10) || 'a to-do');
29
- const more = asks.length - titles.length;
25
+ /** What is said after wrapping up: where the note went, and what was filed, so a mistake can be caught by ear. */
26
+ function filedText(filed: string[], project?: string | null): string {
27
+ const where = project ? ` under ${speakable(project, 6)}` : project === null ? ' with no project' : '';
28
+ if (!filed.length) return `Filed the note${where}.`;
29
+ const titles = filed.slice(0, 3).map((a) => speakable(a, 10) || 'a to-do');
30
+ const more = filed.length - titles.length;
30
31
  const list = more > 0 ? `${titles.join(', ')}, and ${more} more` : titles.length <= 2 ? titles.join(' and ') : `${titles.slice(0, -1).join(', ')} and ${titles[titles.length - 1]}`;
31
- return `Filed the note and ${asks.length} to-do${asks.length === 1 ? '' : 's'}: ${list}.`;
32
+ return `Filed the note${where} and ${filed.length} to-do${filed.length === 1 ? '' : 's'}: ${list}.`;
32
33
  }
33
34
  const NOT_HEARD = 'Sorry, I did not catch that. Can you say that again?';
34
35
  const BRAIN_FAILED = 'I am having trouble thinking right now. Your words are saved. Try again in a moment.';
@@ -103,11 +104,12 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
103
104
  let finish = false;
104
105
  let briefing = record?.briefing;
105
106
  let context = record?.context;
107
+ let pending: ConversationRecord['pending'];
106
108
  if (utterance) {
107
109
  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);
108
110
  const history = lines.slice(-(deps.historyLines ?? DEFAULT_HISTORY_LINES));
109
111
  try {
110
- const out = await deps.brain({ utterance, history, timeZone, now, briefing: record?.briefing ?? null, context: record?.context ?? null });
112
+ const out = await deps.brain({ utterance, history, timeZone, now, briefing: record?.briefing ?? null, context: record?.context ?? null, pending: record?.pending ?? null });
111
113
  replyText = out.text.trim() || NOT_HEARD;
112
114
  did = out.did?.length ? out.did : undefined;
113
115
  forRelay = Boolean(out.forRelay);
@@ -118,6 +120,7 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
118
120
  finish = Boolean(out.finish);
119
121
  if (out.briefing !== undefined) briefing = out.briefing ?? undefined;
120
122
  if (out.context !== undefined) context = out.context ?? undefined;
123
+ pending = out.pending ?? undefined;
121
124
  lap('brain');
122
125
  for (const [k, v] of Object.entries(out.timings ?? {})) timing[`brain.${k}`] = v;
123
126
  } catch (error) {
@@ -136,8 +139,9 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
136
139
  if (finish) {
137
140
  try {
138
141
  const done = await handleConverseEnd(deps, { conversationId });
139
- ended = { ended: true, filed: { note: true, todos: done.asks.length } };
140
- replyText = filedText(done.asks);
142
+ const filedAsks = done.filed ?? done.asks;
143
+ ended = { ended: true, filed: { note: true, todos: filedAsks.length } };
144
+ replyText = filedText(filedAsks, done.project);
141
145
  spokenText = undefined;
142
146
  endedRecord = await store.get(conversationId);
143
147
  } catch (error) {
@@ -176,6 +180,7 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
176
180
  turns: [...(base?.turns ?? []), turn],
177
181
  ...(briefing && !endedRecord ? { briefing } : { briefing: undefined }),
178
182
  ...(context && !endedRecord ? { context } : { context: undefined }),
183
+ ...(pending && !endedRecord ? { pending } : { pending: undefined }),
179
184
  });
180
185
  // The relay finds its work in one list, so a passed-on turn is also recorded there. Never allowed to lose the turn.
181
186
  if (forRelay) await addRelayOrder(deps, { conversation_id: conversationId, turn: n, text: relayText ?? utterance, at: turn.at }).catch((e) => console.error('[converse] relay inbox write failed', e));
@@ -196,7 +201,7 @@ export async function handleConverseEnd(deps: ConverseDeps, req: { conversationI
196
201
  });
197
202
  if (record.status === 'ended') return done(record);
198
203
 
199
- const base = { ...record, briefing: undefined, context: undefined, status: 'ended' as const, endedAt: new Date((deps.now ?? Date.now)()).toISOString() };
204
+ const base = { ...record, briefing: undefined, context: undefined, pending: undefined, status: 'ended' as const, endedAt: new Date((deps.now ?? Date.now)()).toISOString() };
200
205
  let asks: string[] = [];
201
206
  let decisions: string[] = [];
202
207
  const heard = renderWhatHeSaid(base);
@@ -213,6 +218,10 @@ export async function handleConverseEnd(deps: ConverseDeps, req: { conversationI
213
218
  const summary = renderNextSteps(open);
214
219
  const saved = await store.save({ ...withAsks, body: renderTranscript(withAsks), ...(summary ? { summary } : {}) });
215
220
  // Filed like a voice note: under a project, and each ask a to-do. The transcript is already kept, so this never fails End.
216
- if (deps.handoff) await deps.handoff({ record: saved, asks: open, decisions }).catch((error) => console.error('[converse] handoff failed (conversation kept)', error));
217
- return done(saved);
221
+ let project: string | null | undefined;
222
+ if (deps.handoff) {
223
+ const handed = await deps.handoff({ record: saved, asks: open, decisions }).catch((error) => { console.error('[converse] handoff failed (conversation kept)', error); });
224
+ if (handed && 'project' in handed) project = handed.project ?? null;
225
+ }
226
+ return { ...done(saved), filed: open, ...(project !== undefined ? { project } : {}) };
218
227
  }
@@ -25,7 +25,8 @@ export interface ConverseHandoffDeps {
25
25
  }
26
26
 
27
27
  export function createConverseHandoff(deps: ConverseHandoffDeps) {
28
- return async ({ record, asks }: ConverseHandoffInput): Promise<void> => {
28
+ return async ({ record, asks }: ConverseHandoffInput): Promise<{ project: string | null }> => {
29
+ let project: string | null = null;
29
30
  const transcript = record.body ?? '';
30
31
  if (deps.analyzer && transcript) {
31
32
  try {
@@ -35,7 +36,10 @@ export function createConverseHandoff(deps: ConverseHandoffDeps) {
35
36
  transcript, focuses, now: deps.now?.() ?? Date.parse(record.startedAt), ...(record.timeZone ? { timeZone: record.timeZone } : {}),
36
37
  });
37
38
  // Only an id from the offered list files anything.
38
- if (analysis.focusId && focuses.some((f) => f.id === analysis.focusId)) await fileDocument(deps.http, record.id, analysis.focusId);
39
+ if (analysis.focusId && focuses.some((f) => f.id === analysis.focusId)) {
40
+ await fileDocument(deps.http, record.id, analysis.focusId);
41
+ project = focuses.find((f) => f.id === analysis.focusId)?.title ?? null;
42
+ }
39
43
  }
40
44
  } catch (error) {
41
45
  console.error('[converse] filing under a project failed (conversation kept)', error);
@@ -48,5 +52,6 @@ export function createConverseHandoff(deps: ConverseHandoffDeps) {
48
52
  console.error('[converse] to-do extraction failed (conversation kept)', error);
49
53
  }
50
54
  }
55
+ return { project };
51
56
  };
52
57
  }
@@ -1,5 +1,5 @@
1
1
  export { handleConverseTurn, handleConverseEnd } from './handle';
2
- export { converseResponse, converseEndResponse, converseAudioResponse, converseRelayReplyResponse, converseThreadResponse, converseFleetStatusResponse, converseRelayInboxResponse } from './respond';
2
+ export { converseResponse, converseEndResponse, converseAudioResponse, converseRelayReplyResponse, converseThreadResponse, converseFleetStatusResponse, converseFleetViewResponse, converseRelayInboxResponse } from './respond';
3
3
  export { handleRelayInbox, handleRelayReply, handleThread, MAX_RELAY_TEXT } from './relay';
4
4
  export { addRelayOrder, loadRelayOrders, clearRelayOrders, relayInboxExternalId } from './relay-inbox';
5
5
  export type { RelayOrder } from './relay-inbox';
@@ -26,11 +26,13 @@ export type { MeetingConfig } from './meeting-config';
26
26
  export { createUtteranceDetector } from './vad';
27
27
  export type { UtteranceDetector, UtteranceEvent } from './vad';
28
28
  export { createMeetingController } from './meeting';
29
- export type { ListenReason, MeetingApi, MeetingController, MeetingIO, MeetingLine, MeetingPhase, MeetingReply, MeetingState } from './meeting';
29
+ export type { ListenReason, ListenHooks, MeetingApi, MeetingController, MeetingIO, MeetingLine, MeetingPhase, MeetingReply, MeetingState } from './meeting';
30
30
  export { routeUtterance, parseRoute } from './route';
31
31
  export type { ConverseRoute } from './route';
32
- export { saveFleetSnapshot, loadFleetSnapshot, fleetExternalId, FLEET_SOURCE, ageWords, FLEET_FRESH_MS } from './fleet';
32
+ export { cleanFleetInputs, saveFleetSnapshot, loadFleetSnapshot, fleetExternalId, FLEET_SOURCE, ageWords, FLEET_FRESH_MS } from './fleet';
33
33
  export type { FleetSnapshot } from './fleet';
34
+ export { buildFleetView, parseBridgeFind, parseLoops, parsePorts, parseRoles } from './fleet-view';
35
+ export type { FleetInputs, FleetLead, FleetPort, FleetSection, FleetSession, FleetView, RoleRow } from './fleet-view';
34
36
  export { PASSED_TO_RELAY, NO_FLEET_STATUS, NO_FILLER } from './brain';
35
37
  export { ACTIVITY_QUESTION, activityOf, composeActivity, forOwner, loadActivity } from '../activity';
36
38
  export type { Activity, ActivityWindow, ActivityNote } from '../activity';
@@ -13,22 +13,26 @@ export interface MeetingConfig {
13
13
  speechLevel: number;
14
14
  /** The level must hold this long to count as the start of speech. */
15
15
  speechStartMs: number;
16
- /** Speaking during Tandem's reply stops the reply and listens. Default off: the mic ignores the speaker. */
16
+ /** Speaking during Tandem's reply stops the reply and listens (barge-in). Acts only when the io is duplex (echo-cancelled mic). */
17
17
  interruptOnSpeech: boolean;
18
+ /** While the reply is being spoken, the voice must be this loud (0..1 RMS) to count as a barge-in: the speaker leaking into the mic is quieter. */
19
+ bargeInLevel: number;
18
20
  /** While nobody speaks, throw the recorded silence away this often so it never grows. */
19
21
  idleRotateMs: number;
22
+ /** A recording that could not be sent is sent again after this long. */
23
+ resendMs: number;
20
24
  /** How often an open conversation asks whether the relay wrote into it. */
21
25
  relayPollMs: number;
22
26
  }
23
27
 
24
28
  export const MEETING_DEFAULTS: MeetingConfig = {
25
- silenceMs: 1200, minUtteranceMs: 400, maxUtteranceMs: 60_000, speechLevel: 0.02, speechStartMs: 150,
26
- interruptOnSpeech: false, idleRotateMs: 30_000, relayPollMs: 4000,
29
+ silenceMs: 1200, minUtteranceMs: 400, maxUtteranceMs: 60_000, speechLevel: 0.02, speechStartMs: 150, bargeInLevel: 0.08,
30
+ interruptOnSpeech: true, idleRotateMs: 30_000, relayPollMs: 4000, resendMs: 3000,
27
31
  };
28
32
 
29
33
  export function resolveMeetingConfig(over: Partial<MeetingConfig> = {}): MeetingConfig {
30
34
  const out: MeetingConfig = { ...MEETING_DEFAULTS };
31
- for (const key of ['silenceMs', 'minUtteranceMs', 'maxUtteranceMs', 'speechLevel', 'speechStartMs', 'idleRotateMs', 'relayPollMs'] as const) {
35
+ for (const key of ['silenceMs', 'minUtteranceMs', 'maxUtteranceMs', 'speechLevel', 'speechStartMs', 'bargeInLevel', 'idleRotateMs', 'relayPollMs', 'resendMs'] as const) {
32
36
  const v = over[key];
33
37
  if (typeof v === 'number' && Number.isFinite(v) && v > 0) out[key] = v;
34
38
  }
@@ -34,6 +34,8 @@ export interface MeetingState {
34
34
  relayNotice: string | null;
35
35
  /** The small mic: true = the meeting listens; false = it does not (typing still works). */
36
36
  micOn: boolean;
37
+ /** True while the microphone is actually open. With a duplex io it stays true while the reply is thought about and spoken. */
38
+ micLive: boolean;
37
39
  }
38
40
 
39
41
  /** Why `listen` returned: the platform's detector says, the controller only needs `audio` and `cancelled`. */
@@ -50,15 +52,24 @@ export interface MeetingApi<A = Blob> {
50
52
  /** What `speak` is given: everything about the reply, so the platform fetches (with its bearer) and plays the bytes. */
51
53
  export interface MeetingReply { conversationId: string; turn: number; replyText: string; audioUrl: string }
52
54
 
55
+ export interface ListenHooks {
56
+ /** Called when the voice starts (a barge-in when the reply is being spoken). */
57
+ onSpeechStart?: () => void;
58
+ }
59
+
53
60
  export interface MeetingIO<A = Blob> {
61
+ /** True when the microphone can stay open while the reply is spoken (echo-cancelled). The loop then never stops listening for a reply. */
62
+ duplex?: boolean;
54
63
  /** Resolves when one utterance is over (end of speech) with its recording, or `{audio: null}` when there was none or it was cancelled. */
55
- listen(signal: AbortSignal, config: MeetingConfig): Promise<{ audio: A | null; cancelled?: boolean; reason?: ListenReason }>;
64
+ listen(signal: AbortSignal, config: MeetingConfig, hooks?: ListenHooks): Promise<{ audio: A | null; cancelled?: boolean; reason?: ListenReason }>;
56
65
  /** Plays the reply and resolves when it has finished (or was stopped); never rejects the loop. `signal` aborts it. */
57
66
  speak(reply: MeetingReply, signal: AbortSignal, config: MeetingConfig): Promise<void>;
58
67
  }
59
68
 
60
69
  export interface MeetingController {
61
70
  start(): void;
71
+ /** The Stop button: cuts off the reply being spoken (or about to be) and goes back to listening. The text stays on screen. */
72
+ stop(): void;
62
73
  /** The mic control. On: listen (starting the meeting if needed, keeping the open conversation). Off: stop listening and SEND what was said so far; the conversation stays open. */
63
74
  mic(on: boolean): void;
64
75
  getState(): MeetingState;
@@ -82,7 +93,8 @@ export function createMeetingController<A = Blob>(options: {
82
93
  }): MeetingController {
83
94
  const { client, io } = options;
84
95
  const config = resolveMeetingConfig(options.config);
85
- let s: MeetingState = { phase: 'idle', retryable: false, lines: [], error: null, noAudio: null, conversationId: null, saved: null, relayNotice: null, micOn: false };
96
+ let s: MeetingState = { phase: 'idle', retryable: false, lines: [], error: null, noAudio: null, conversationId: null, saved: null, relayNotice: null, micOn: false, micLive: false };
97
+ const duplex = options.io.duplex === true;
86
98
  let running = false;
87
99
  /** Wakes the loop when the mic is turned back on. */
88
100
  let resume: (() => void) | null = null;
@@ -90,6 +102,8 @@ export function createMeetingController<A = Blob>(options: {
90
102
  let listenAbort = new AbortController();
91
103
  let speakAbort = new AbortController();
92
104
  let lastReply: MeetingReply | null = null;
105
+ /** Bumped by stop(): a reply whose turn began before it is shown but not spoken. */
106
+ let stopEpoch = 0;
93
107
  /** The newest turn number this meeting has seen, its own or the relay's. */
94
108
  let seen = 0;
95
109
  /** While a relay message is being spoken, listening waits. */
@@ -103,9 +117,20 @@ export function createMeetingController<A = Blob>(options: {
103
117
  const restPhase = (): MeetingPhase => (s.micOn ? 'listening' : 'idle');
104
118
 
105
119
  const listeners = new Set<(state: MeetingState) => void>();
106
- const set = (patch: Partial<MeetingState>) => { s = { ...s, ...patch }; options.onChange?.(s); listeners.forEach((l) => l(s)); };
120
+ /** The mic is live while listening, and (duplex) also while thinking and speaking. */
121
+ const liveNow = (next: MeetingState) => running && next.micOn && (duplex ? ['listening', 'thinking', 'speaking', 'idle'].includes(next.phase) : next.phase === 'listening');
122
+ const set = (patch: Partial<MeetingState>) => { s = { ...s, ...patch }; s = { ...s, micLive: liveNow(s) }; options.onChange?.(s); listeners.forEach((l) => l(s)); };
123
+
124
+ /** A phone that cannot record and play at once stops listening for a reply; a duplex io keeps the mic open. */
125
+ /** `finish`: if he was speaking, what he said so far is SENT, never discarded. */
126
+ const pauseListening = () => { if (!duplex) listenAbort.abort('finish'); };
127
+
128
+ /** True from the moment he starts talking until his utterance is handed over. */
129
+ let userSpeaking = false;
107
130
 
108
131
  async function playReply(reply: MeetingReply) {
132
+ // A reply (a relay message, a slow answer) never talks over him: wait until his utterance is over.
133
+ while (duplex && running && userSpeaking) await new Promise((r) => setTimeout(r, 50));
109
134
  speakAbort = new AbortController();
110
135
  set({ phase: 'speaking', noAudio: null });
111
136
  try {
@@ -113,11 +138,13 @@ export function createMeetingController<A = Blob>(options: {
113
138
  } catch (e) {
114
139
  set({ noAudio: `${e instanceof Error ? e.message : 'playback failed'}` });
115
140
  }
141
+ if (duplex && running && s.phase === 'speaking') set({ phase: restPhase() });
116
142
  }
117
143
 
118
144
  /** Sends one turn; resolves true when it produced a reply. Never throws except to stop the meeting. */
119
- async function takeTurn(input: { audio?: A; text?: string }): Promise<boolean> {
120
- const turnId = freshId();
145
+ async function takeTurn(input: { audio?: A; text?: string }, again?: string): Promise<boolean> {
146
+ const turnId = again ?? freshId();
147
+ const epoch = stopEpoch;
121
148
  set({ phase: 'thinking', error: null, retryable: false });
122
149
  for (let attempt = 0; attempt < 2; attempt += 1) {
123
150
  try {
@@ -143,7 +170,7 @@ export function createMeetingController<A = Blob>(options: {
143
170
  if (out.audio_url) {
144
171
  lastReply = { conversationId: out.conversation_id, turn: out.turn, replyText: out.reply_text, audioUrl: out.audio_url };
145
172
  // A typed message speaks its reply even before Start: the person asked in text, but the screen is a voice one.
146
- if (running || input.text) await playReply(lastReply);
173
+ if ((running || input.text) && epoch === stopEpoch) await playReply(lastReply);
147
174
  } else {
148
175
  lastReply = null;
149
176
  set({ noAudio: out.audio_reason ?? 'no audio was produced' });
@@ -153,6 +180,8 @@ export function createMeetingController<A = Blob>(options: {
153
180
  if (isRejected(e)) { set({ phase: 'stopped', micOn: false, error: e instanceof Error ? e.message : 'The session ended.' }); running = false; return false; }
154
181
  if (attempt === 1 || !(e instanceof ConverseClientError && e.retryable)) {
155
182
  set({ error: e instanceof Error ? e.message : 'That turn failed.', retryable: e instanceof ConverseClientError && e.retryable });
183
+ // What he said is never thrown away: the same recording is sent again (same turn id, so the server never doubles it).
184
+ if (input.audio && running) scheduleResend(input, turnId);
156
185
  return false;
157
186
  }
158
187
  // retryable (mis-heard): one more try with the SAME turn id, so the server never doubles it
@@ -161,6 +190,15 @@ export function createMeetingController<A = Blob>(options: {
161
190
  return false;
162
191
  }
163
192
 
193
+ /** Sends a recording that failed again after a pause, until it goes through or the meeting ends. */
194
+ function scheduleResend(input: { audio?: A; text?: string }, turnId: string) {
195
+ setTimeout(() => {
196
+ if (!running) return;
197
+ const turn = turnChain.then(() => (running ? takeTurn(input, turnId) : false));
198
+ turnChain = turn.catch(() => undefined);
199
+ }, config.resendMs);
200
+ }
201
+
164
202
  /** Asks for turns past `seen`; relay ones are shown and, in a running meeting, spoken at once. */
165
203
  async function pollOnce() {
166
204
  const id = s.conversationId;
@@ -179,7 +217,7 @@ export function createMeetingController<A = Blob>(options: {
179
217
  const reply: MeetingReply = { conversationId: id, turn: t.turn, replyText: t.reply_text, audioUrl: t.audio_url };
180
218
  const done = turnChain.then(async () => {
181
219
  if (!running) return;
182
- listenAbort.abort();
220
+ pauseListening();
183
221
  await playReply(reply);
184
222
  if (running && s.phase === 'speaking') set({ phase: restPhase() });
185
223
  });
@@ -213,8 +251,15 @@ export function createMeetingController<A = Blob>(options: {
213
251
  continue;
214
252
  }
215
253
  listenAbort = new AbortController();
216
- set({ phase: 'listening' });
217
- const heard = await io.listen(listenAbort.signal, config);
254
+ if (!duplex || s.phase === 'idle') set({ phase: 'listening' });
255
+ const heard = await io.listen(listenAbort.signal, config, {
256
+ // Barge-in: the person starts talking while the reply is being read: cut it off, what they say is the next turn.
257
+ onSpeechStart: () => {
258
+ userSpeaking = true;
259
+ if (duplex && config.interruptOnSpeech && s.phase === 'speaking') speakAbort.abort('barge-in');
260
+ },
261
+ });
262
+ userSpeaking = false;
218
263
  if (!running) break;
219
264
  // An io with no microphone cancels by itself: wait for End (typing still works) instead of spinning.
220
265
  if (heard.cancelled && !listenAbort.signal.aborted) {
@@ -224,6 +269,11 @@ export function createMeetingController<A = Blob>(options: {
224
269
  if (!heard.audio) continue;
225
270
  const turn = turnChain.then(() => takeTurn({ audio: heard.audio as A }));
226
271
  turnChain = turn.catch(() => undefined);
272
+ // Duplex: listening goes on while the turn runs and the reply is spoken, so a new utterance is picked up at once.
273
+ if (duplex) {
274
+ void turn.then(() => { if (running && s.phase === 'thinking') set({ phase: restPhase() }); }, () => undefined);
275
+ continue;
276
+ }
227
277
  await turn;
228
278
  }
229
279
  }
@@ -249,6 +299,11 @@ export function createMeetingController<A = Blob>(options: {
249
299
  getState: () => s,
250
300
  subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
251
301
  start() { begin(true); },
302
+ stop() {
303
+ stopEpoch += 1;
304
+ speakAbort.abort('stop');
305
+ if (running && s.phase === 'speaking') set({ phase: restPhase() });
306
+ },
252
307
  mic(on) {
253
308
  if (on) {
254
309
  // Typing before the mic: the conversation is already open, so turning the mic on continues it.
@@ -268,7 +323,7 @@ export function createMeetingController<A = Blob>(options: {
268
323
  // The microphone is still open here: stop listening before the reply plays (a phone cannot record and play in one session),
269
324
  // and hold the loop (`gate`) until the reply is done, exactly like a relay message.
270
325
  const done = turnChain.then(async () => {
271
- if (running) listenAbort.abort();
326
+ if (running) pauseListening();
272
327
  await takeTurn({ text: t });
273
328
  if (running && s.phase !== 'stopped') set({ phase: restPhase() });
274
329
  else if (!running && (s.phase === 'thinking' || s.phase === 'speaking')) set({ phase: 'idle' });
@@ -282,7 +337,7 @@ export function createMeetingController<A = Blob>(options: {
282
337
  if (!lastReply) return;
283
338
  const reply = lastReply;
284
339
  const done = turnChain.then(async () => {
285
- if (running) listenAbort.abort();
340
+ if (running) pauseListening();
286
341
  await playReply(reply);
287
342
  if (running) set({ phase: restPhase() });
288
343
  });
@@ -7,7 +7,8 @@
7
7
  import { isTimeZone } from '../spoken-time';
8
8
  import { voiceErrorResponse } from '../voice-manage';
9
9
  import { handleConverseEnd, handleConverseTurn } from './handle';
10
- import { saveFleetSnapshot } from './fleet';
10
+ import { cleanFleetInputs, loadFleetSnapshot, saveFleetSnapshot } from './fleet';
11
+ import { buildFleetView } from './fleet-view';
11
12
  import { handleRelayInbox, handleRelayReply, handleThread } from './relay';
12
13
  import { createEntityConversationStore } from './store';
13
14
  import { CLIENT_ID, ConverseError, MAX_CONVERSE_AUDIO_BYTES, type ConverseDeps, type ConverseTurnRequest } from './types';
@@ -138,13 +139,24 @@ export async function converseThreadResponse(conversationId: string, after: stri
138
139
  export async function converseFleetStatusResponse(request: Request, deps: ConverseDeps): Promise<Response> {
139
140
  try {
140
141
  const { fields } = await fieldsOf(request);
141
- const saved = await saveFleetSnapshot(deps, typeof fields.text === 'string' ? fields.text : '');
142
+ const saved = await saveFleetSnapshot(deps, typeof fields.text === 'string' ? fields.text : '', cleanFleetInputs(fields.inputs));
142
143
  return Response.json({ saved: true, record_id: saved.record_id, updated_at: saved.updatedAt });
143
144
  } catch (error) {
144
145
  return failure(error);
145
146
  }
146
147
  }
147
148
 
149
+ /** GET /corpus/converse/fleet-status: the snapshot as the /fleet page reads it ({text, updatedAt, view}); `snapshot: null` before the relay has posted. */
150
+ export async function converseFleetViewResponse(deps: ConverseDeps): Promise<Response> {
151
+ try {
152
+ const snap = await loadFleetSnapshot(deps);
153
+ const body = snap ? { snapshot: { text: snap.text, updatedAt: snap.updatedAt, view: snap.inputs ? buildFleetView(snap.inputs) : null } } : { snapshot: null };
154
+ return Response.json(body, { headers: { 'cache-control': 'no-store' } });
155
+ } catch (error) {
156
+ return failure(error);
157
+ }
158
+ }
159
+
148
160
  /** GET /corpus/converse/relay-inbox: what the person has asked the relay for that it has not answered yet. */
149
161
  export async function converseRelayInboxResponse(deps: ConverseDeps): Promise<Response> {
150
162
  try {
@@ -8,10 +8,17 @@ import { IDENTIFIER } from '../briefing/speak';
8
8
  const ISO_DATE = /\b(\d{4}-\d{2}-\d{2})\b/g;
9
9
  const MARKUP = /[*_#`~<>|\\]|\[|\]|^\s*[-•>]\s/m;
10
10
 
11
+ /** "Yes, the to-do ..." / "Sure, ..." / "Okay. ...": an answer says the answer, not that it agrees. Voice only. */
12
+ const FILLER = /^(?:(?:yes|yeah|yep|sure|okay|ok|certainly|of course|absolutely|right|alright)\b[,.!]?\s+)+/i;
13
+ const LABEL = /^(?:the |your )?(?:to-?do|task|item|reminder)\s+(?=\S)/i;
14
+ const capital = (s: string) => (s ? s[0].toUpperCase() + s.slice(1) : s);
15
+
11
16
  export function toSpoken(text: string, today: string): string | null {
12
- if (!ISO_DATE.test(text) && !new RegExp(IDENTIFIER.source).test(text) && !MARKUP.test(text)) { ISO_DATE.lastIndex = 0; return null; }
17
+ const lead = text.replace(FILLER, (m) => (m ? '' : m));
18
+ const stripped = lead !== text ? capital(lead.replace(LABEL, '')) : text;
19
+ if (stripped === text && !ISO_DATE.test(text) && !new RegExp(IDENTIFIER.source).test(text) && !MARKUP.test(text)) { ISO_DATE.lastIndex = 0; return null; }
13
20
  ISO_DATE.lastIndex = 0;
14
- const out = text
21
+ const out = stripped
15
22
  .replace(ISO_DATE, (d) => spokenWhen(d, today))
16
23
  .replace(/\s*\(\s*[A-Za-z]{2,10}-\d+\s*\)/g, '')
17
24
  .replace(IDENTIFIER, '')
@@ -1,16 +1,24 @@
1
1
  /**
2
2
  * What is SAID aloud for a long answer (Quinn: short, like a meeting). The full answer stays on the screen; the voice says
3
- * the first three items and "and N more", or the first sentences and "The rest is on your screen." Short answers are
4
- * said whole (this returns undefined).
3
+ * the first three items and "and N more", or the first sentences, and then asks "Want the rest?". Saying yes reads the
4
+ * remainder the same way (`spokenRest`), again a short piece at a time. Short answers are said whole (undefined).
5
5
  */
6
6
  const WORDS = (s: string) => s.trim().split(/\s+/).filter(Boolean);
7
- const SPOKEN_MAX_WORDS = 45;
7
+ const SPOKEN_MAX_WORDS = 30;
8
8
  const LIST_AT = 4;
9
+ const OFFER = 'Want the rest?';
9
10
 
10
11
  const finish = (s: string) => s.replace(/\s+/g, ' ').trim().replace(/[,;:]+$/, '');
11
12
  const endWithStop = (s: string) => (/[.!?]$/.test(s) ? s : `${s}.`);
12
13
 
13
- export function spokenSummary(answer: string): string | undefined {
14
+ export interface SplitAnswer {
15
+ /** What the voice says now, ending in the offer. */
16
+ spoken: string;
17
+ /** What has not been said yet (the text a "yes" reads next). */
18
+ rest: string;
19
+ }
20
+
21
+ export function splitAnswer(answer: string): SplitAnswer | undefined {
14
22
  const text = answer.replace(/\s+/g, ' ').trim();
15
23
  if (!text) return undefined;
16
24
 
@@ -21,7 +29,10 @@ export function spokenSummary(answer: string): string | undefined {
21
29
  const intro = finish(text.slice(0, first));
22
30
  const items = markers.map((m, i) => finish(text.slice((m.index ?? 0) + m[0].length, markers[i + 1]?.index ?? text.length)).replace(/[.]+$/, ''));
23
31
  const head = items.slice(0, 3).map((x) => endWithStop(x)).join(' ');
24
- return `${intro ? `${endWithStop(intro)} ` : ''}${head} And ${items.length - 3} more.`;
32
+ return {
33
+ spoken: `${intro ? `${endWithStop(intro)} ` : ''}${head} And ${items.length - 3} more. ${OFFER}`,
34
+ rest: items.slice(3).map((x) => endWithStop(x)).join(' '),
35
+ };
25
36
  }
26
37
 
27
38
  const words = WORDS(text);
@@ -30,14 +41,25 @@ export function spokenSummary(answer: string): string | undefined {
30
41
  // Prose: whole sentences up to the limit; if the first sentence alone is too long (a list run together with commas), cut it at a comma.
31
42
  const sentences = text.match(/[^.!?]+[.!?]+(?:\s|$)|[^.!?]+$/g)?.map((s) => s.trim()).filter(Boolean) ?? [text];
32
43
  let spoken = '';
44
+ let used = 0;
33
45
  for (const s of sentences) {
34
46
  if (WORDS(`${spoken} ${s}`).length > SPOKEN_MAX_WORDS) break;
35
47
  spoken = `${spoken} ${s}`.trim();
48
+ used += 1;
36
49
  }
37
50
  if (!spoken) {
38
- const cut = words.slice(0, 38).join(' ');
51
+ const cut = words.slice(0, 26).join(' ');
39
52
  const at = Math.max(cut.lastIndexOf(','), cut.lastIndexOf(';'));
40
- spoken = endWithStop(finish(at > 15 ? cut.slice(0, at) : cut));
53
+ const said = at > 12 ? cut.slice(0, at) : cut;
54
+ return { spoken: `${endWithStop(finish(said))} ${OFFER}`, rest: finish(text.slice(said.length).replace(/^[\s,;:]+/, '')) };
41
55
  }
42
- return `${spoken} The rest is on your screen.`;
56
+ return { spoken: `${spoken} ${OFFER}`, rest: sentences.slice(used).join(' ').trim() };
43
57
  }
58
+
59
+ export const spokenSummary = (answer: string): string | undefined => splitAnswer(answer)?.spoken;
60
+
61
+ /** The remainder after the part `spokenSummary` said, or undefined when the whole answer was said. */
62
+ export const spokenRest = (answer: string): string | undefined => splitAnswer(answer)?.rest || undefined;
63
+
64
+ /** "yes", "go on", "the rest": the person wants what was left out. Only ever tried right after a shortened answer. */
65
+ export const WANTS_THE_REST = /^(?:(?:yes|yeah|yep|yup|sure|ok(?:ay)?|please|go on|go ahead|continue|keep going|read (?:it|the rest|more)|the rest|tell me more|more|and then)\b[\s,.!]*){1,4}$/i;
@@ -32,6 +32,7 @@ function toRecord(entity: TenantEntity): ConversationRecord {
32
32
  ...(d.decisions ? { decisions: list(d.decisions) } : {}),
33
33
  ...(d.briefing && typeof d.briefing === 'object' ? { briefing: d.briefing as ConversationRecord['briefing'] } : {}),
34
34
  ...(d.context && typeof d.context === 'object' ? { context: d.context as ConversationRecord['context'] } : {}),
35
+ ...(d.pending && typeof d.pending === 'object' ? { pending: d.pending as ConversationRecord['pending'] } : {}),
35
36
  };
36
37
  }
37
38
 
@@ -72,6 +73,7 @@ export function createEntityConversationStore(http: ConverseDeps['http'], ownerS
72
73
  ...(record.decisions ? { decisions: record.decisions } : {}),
73
74
  briefing: record.briefing ?? null,
74
75
  context: record.context ?? null,
76
+ pending: record.pending ?? null,
75
77
  },
76
78
  });
77
79
  return { ...record, id: String(row.id) };