@startsimpli/integrations 0.2.197 → 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.
- package/package.json +7 -7
- package/src/__tests__/briefing-actions.test.ts +11 -0
- package/src/__tests__/briefing-edits.test.ts +98 -0
- package/src/__tests__/converse-brain.test.ts +64 -1
- package/src/__tests__/converse-handoff.test.ts +8 -0
- package/src/__tests__/converse-meeting-brief.test.ts +72 -8
- package/src/__tests__/converse-meeting-duplex.test.ts +132 -0
- package/src/__tests__/converse-meeting-keep-speech.test.ts +87 -0
- package/src/__tests__/converse-meeting-vad.test.ts +1 -1
- package/src/__tests__/converse-spoken-form.test.ts +10 -0
- package/src/__tests__/converse-spoken-summary.test.ts +27 -6
- package/src/__tests__/converse.test.ts +29 -2
- package/src/__tests__/corpus-ask-items.test.ts +14 -0
- package/src/__tests__/corpus-ask.test.ts +22 -0
- package/src/__tests__/corpus-tracker.test.tsx +12 -0
- package/src/__tests__/extract-classify.test.ts +17 -0
- package/src/__tests__/fleet-page.test.tsx +57 -0
- package/src/__tests__/fleet-view.test.ts +149 -0
- package/src/__tests__/project-basis-entity.test.ts +19 -0
- package/src/__tests__/project-basis.test.ts +21 -0
- package/src/__tests__/relay-cli.test.ts +10 -1
- package/src/__tests__/spoken-time.test.ts +4 -0
- package/src/__tests__/task-detail-project-guess.test.tsx +46 -0
- package/src/__tests__/voice-due-later-sentence.test.ts +26 -0
- package/src/components/index.ts +2 -0
- package/src/components/pages/FleetPage.tsx +115 -0
- package/src/components/pages/TaskDetailPage.tsx +27 -1
- package/src/components/pages/TrackerPage.tsx +1 -1
- package/src/components/pages/task-tracker/ProjectGuess.tsx +42 -0
- package/src/corpus/ask-items-intent.ts +24 -0
- package/src/corpus/ask-items.ts +7 -4
- package/src/corpus/ask.ts +1 -1
- package/src/corpus/briefing/actions/confirm.ts +9 -1
- package/src/corpus/briefing/actions/execute.ts +71 -11
- package/src/corpus/briefing/actions/log.ts +1 -1
- package/src/corpus/briefing/actions/seam.ts +18 -2
- package/src/corpus/briefing/actions/types.ts +14 -0
- package/src/corpus/briefing/intent/describe.ts +5 -1
- package/src/corpus/briefing/intent/edits.ts +92 -0
- package/src/corpus/briefing/intent/grammar.ts +3 -0
- package/src/corpus/briefing/intent/ground.ts +5 -1
- package/src/corpus/briefing/intent/match.ts +3 -1
- package/src/corpus/briefing/intent/model.ts +36 -3
- package/src/corpus/briefing/intent/resolve.ts +12 -1
- package/src/corpus/briefing/intent/types.ts +8 -0
- package/src/corpus/briefing/speak.ts +13 -0
- package/src/corpus/client.ts +2 -0
- package/src/corpus/converse/brain.ts +41 -13
- package/src/corpus/converse/briefing-queue.ts +105 -27
- package/src/corpus/converse/client.ts +6 -0
- package/src/corpus/converse/fleet-view.ts +126 -0
- package/src/corpus/converse/fleet.ts +18 -5
- package/src/corpus/converse/followups.ts +12 -2
- package/src/corpus/converse/handle.ts +21 -12
- package/src/corpus/converse/handoff.ts +7 -2
- package/src/corpus/converse/index.ts +5 -3
- package/src/corpus/converse/meeting-config.ts +8 -4
- package/src/corpus/converse/meeting.ts +66 -11
- package/src/corpus/converse/respond.ts +14 -2
- package/src/corpus/converse/spoken-form.ts +9 -2
- package/src/corpus/converse/spoken-summary.ts +30 -8
- package/src/corpus/converse/store.ts +2 -0
- package/src/corpus/converse/types.ts +14 -1
- package/src/corpus/entities.ts +2 -0
- package/src/corpus/extract.ts +9 -4
- package/src/corpus/project-basis.ts +23 -0
- package/src/corpus/spoken-time.ts +18 -2
- package/src/corpus/types.ts +6 -0
- package/src/corpus/voice-due.ts +24 -0
- package/src/native/app/converseServices.ts +5 -3
- package/src/native/app/device.ts +2 -0
- package/src/native/converse/ConverseScreen.tsx +28 -0
- package/src/native/converse/__tests__/liveScreen.test.tsx +35 -2
- package/src/native/converse/__tests__/meetingIO.test.ts +55 -1
- package/src/native/converse/format.ts +2 -2
- package/src/native/converse/io.ts +15 -5
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* (an <audio src> cannot send one). No React, no DOM beyond fetch/FormData, so the web page and the native
|
|
4
4
|
* tab call the same thing.
|
|
5
5
|
*/
|
|
6
|
+
import type { FleetView } from './fleet-view';
|
|
6
7
|
import type { ConverseEndResult, ConverseThread, ConverseTurnResult } from './types';
|
|
7
8
|
|
|
8
9
|
export class ConverseClientError extends Error {
|
|
@@ -19,6 +20,8 @@ export interface ConverseClient {
|
|
|
19
20
|
end(conversationId: string): Promise<ConverseEndResult>;
|
|
20
21
|
/** The thread from turn `after` + 1 on: how a page finds out the relay wrote into it. */
|
|
21
22
|
thread(conversationId: string, after: number): Promise<ConverseThread>;
|
|
23
|
+
/** The relay's fleet snapshot, parsed (`snapshot: null` before the relay has posted). */
|
|
24
|
+
fleet(): Promise<{ snapshot: { text: string; updatedAt: string; view: FleetView | null } | null }>;
|
|
22
25
|
/** Fetches a turn's audio and returns an object URL to play. */
|
|
23
26
|
audioUrl(path: string): Promise<string>;
|
|
24
27
|
}
|
|
@@ -53,6 +56,9 @@ export function createConverseClient(options: {
|
|
|
53
56
|
body.append('timeZone', timeZone || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC');
|
|
54
57
|
return (await (await call(base, { method: 'POST', body }, 'That turn failed')).json()) as ConverseTurnResult;
|
|
55
58
|
},
|
|
59
|
+
async fleet() {
|
|
60
|
+
return (await (await call(`${base}/fleet-status`, { method: 'GET', cache: 'no-store' }, 'Could not load the fleet')).json()) as Awaited<ReturnType<ConverseClient['fleet']>>;
|
|
61
|
+
},
|
|
56
62
|
async end(conversationId) {
|
|
57
63
|
return (await (await call(`${base}/end`, {
|
|
58
64
|
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ conversation_id: conversationId }),
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fleet as structure, not prose (Tandem /fleet). The relay posts three RAW inputs next to the text snapshot:
|
|
3
|
+
* `roles.md` (who leads what), the open-loops ledger (what waits on whom) and `bridge find ""` (who is live and what each
|
|
4
|
+
* is for). This module is the ONE parser: relay -> role leads -> the sessions each lead owns, then everyone else.
|
|
5
|
+
*/
|
|
6
|
+
export interface FleetInputs { roles?: string; loops?: string; sessions?: string; ports?: string }
|
|
7
|
+
export interface FleetSection { title: string; items: string[] }
|
|
8
|
+
export interface FleetPort { project: string; range: string; base: string; url: string | null; notes: string }
|
|
9
|
+
|
|
10
|
+
export interface FleetSession { id: string; name: string; machine: string; goal: string; repo: string; branch: string; status: 'live' | 'dormant' }
|
|
11
|
+
export interface RoleRow { role: string; sessionId: string | null; childIds: string[]; notes: string }
|
|
12
|
+
export interface FleetLead { role: string; notes: string; session: FleetSession | null; children: FleetSession[]; /** The id roles.md lists, when it is not the live one. */ listedId?: string }
|
|
13
|
+
export interface FleetView {
|
|
14
|
+
relay: FleetSession | null;
|
|
15
|
+
leads: FleetLead[];
|
|
16
|
+
others: FleetSession[];
|
|
17
|
+
waitingOnQuinn: string[];
|
|
18
|
+
waitingOnSessions: string[];
|
|
19
|
+
rolesUpdated: string | null;
|
|
20
|
+
loopsUpdated: string | null;
|
|
21
|
+
ports: FleetPort[];
|
|
22
|
+
/** The ledger's other headed sections (state notes, parked items, ...), in file order. */
|
|
23
|
+
sections: FleetSection[];
|
|
24
|
+
/** Hand-edited markdown that did not fit: shown as-is, never a failure. */
|
|
25
|
+
unparsed: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const HEX8 = /\b[0-9a-f]{8}\b/g;
|
|
29
|
+
const updatedOf = (md: string) => /^Updated\s+(.+)$/m.exec(md)?.[1].trim() ?? null;
|
|
30
|
+
|
|
31
|
+
export function parseRoles(md: string): { updated: string | null; rows: RoleRow[]; unparsed: string[] } {
|
|
32
|
+
const rows: RoleRow[] = [];
|
|
33
|
+
const unparsed: string[] = [];
|
|
34
|
+
for (const line of md.split('\n')) {
|
|
35
|
+
const t = line.trim();
|
|
36
|
+
if (t && !t.startsWith('|') && !t.startsWith('#') && !/^Updated\s/.test(t)) unparsed.push(t);
|
|
37
|
+
if (!t.startsWith('|')) continue;
|
|
38
|
+
const cells = line.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
|
|
39
|
+
if (/^[-:\s]+$/.test(cells.join('')) || cells[0].toLowerCase() === 'role') continue;
|
|
40
|
+
if (cells.length < 2 || !cells[0]) { unparsed.push(t); continue; }
|
|
41
|
+
const [role, live, notes = ''] = cells;
|
|
42
|
+
const sessionId = /^none/i.test(live) ? null : live.match(HEX8)?.[0] ?? null;
|
|
43
|
+
const childIds = [...new Set(notes.match(HEX8) ?? [])].filter((id) => id !== sessionId);
|
|
44
|
+
rows.push({ role, sessionId, childIds, notes });
|
|
45
|
+
}
|
|
46
|
+
return { updated: updatedOf(md), rows, unparsed };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function parseLoops(md: string): { updated: string | null; waitingOnQuinn: string[]; waitingOnSessions: string[]; sections: FleetSection[]; unparsed: string[] } {
|
|
50
|
+
const out = { updated: updatedOf(md), waitingOnQuinn: [] as string[], waitingOnSessions: [] as string[], sections: [] as FleetSection[], unparsed: [] as string[] };
|
|
51
|
+
let into: string[] | null = null;
|
|
52
|
+
for (const line of md.split('\n')) {
|
|
53
|
+
const h = /^#{2,}\s+(.*)$/.exec(line);
|
|
54
|
+
if (h) {
|
|
55
|
+
const title = h[1].trim();
|
|
56
|
+
if (/^waiting on quinn/i.test(title)) into = out.waitingOnQuinn;
|
|
57
|
+
else if (/^(waiting on sessions|relay owes)/i.test(title)) into = out.waitingOnSessions;
|
|
58
|
+
else { const sec = { title, items: [] as string[] }; out.sections.push(sec); into = sec.items; }
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const t = line.trim();
|
|
62
|
+
const b = /^[-*]\s+(.+)$/.exec(t);
|
|
63
|
+
if (b && into) into.push(b[1].trim());
|
|
64
|
+
else if (t && !t.startsWith('#') && !/^Updated\s/.test(t)) (into ?? out.unparsed).push(t);
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** ports.md table: | Project | Range | Base (...) | Notes |; the URL is the first 4-digit port in the Base cell. */
|
|
70
|
+
export function parsePorts(md: string): FleetPort[] {
|
|
71
|
+
const out: FleetPort[] = [];
|
|
72
|
+
for (const line of md.split('\n')) {
|
|
73
|
+
const t = line.trim();
|
|
74
|
+
if (!t.startsWith('|')) continue;
|
|
75
|
+
const cells = t.replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
|
|
76
|
+
if (cells.length < 3 || /^[-:\s]+$/.test(cells.join('')) || cells[0].toLowerCase() === 'project') continue;
|
|
77
|
+
const port = /\b(\d{4,5})\b/.exec(cells[2])?.[1];
|
|
78
|
+
out.push({ project: cells[0], range: cells[1], base: cells[2], url: port ? `http://localhost:${port}` : null, notes: cells[3] ?? '' });
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** `bridge find ""` lines: [live] `machine · name · id` goal repo@branch [model ..] */
|
|
84
|
+
export function parseBridgeFind(out: string): FleetSession[] {
|
|
85
|
+
const sessions: FleetSession[] = [];
|
|
86
|
+
for (const line of out.split('\n')) {
|
|
87
|
+
const m = /^\[(live|dormant)\]\s+`([^`]+)`\s*(.*)$/.exec(line);
|
|
88
|
+
if (!m) continue;
|
|
89
|
+
const parts = m[2].split(' · ').map((p) => p.trim());
|
|
90
|
+
const id = parts[parts.length - 1];
|
|
91
|
+
if (!/^[0-9a-f]{8}$/.test(id)) continue; // spawn runners and anything without a session id
|
|
92
|
+
const segs = m[3].split(/\s{2,}/).map((s) => s.trim()).filter(Boolean);
|
|
93
|
+
const rb = segs.find((s) => /^[^\s@]+@\S+$/.test(s)) ?? '';
|
|
94
|
+
const goal = segs[0] && segs[0] !== rb && !segs[0].startsWith('[') ? segs[0] : '';
|
|
95
|
+
const [repo = '', ...br] = rb.split('@');
|
|
96
|
+
sessions.push({ id, machine: parts[0] ?? '', name: parts.slice(1, -1).join(' · '), goal, repo, branch: br.join('@'), status: m[1] as 'live' | 'dormant' });
|
|
97
|
+
}
|
|
98
|
+
return sessions;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function buildFleetView(inputs: FleetInputs): FleetView {
|
|
102
|
+
const roles = parseRoles(inputs.roles ?? '');
|
|
103
|
+
const loops = parseLoops(inputs.loops ?? '');
|
|
104
|
+
const sessions = parseBridgeFind(inputs.sessions ?? '');
|
|
105
|
+
const ports = parsePorts(inputs.ports ?? '');
|
|
106
|
+
const byId = new Map(sessions.map((s) => [s.id, s]));
|
|
107
|
+
const used = new Set<string>();
|
|
108
|
+
const take = (id: string | null) => { const s = id ? byId.get(id) ?? null : null; if (s) used.add(s.id); return s; };
|
|
109
|
+
let relay: FleetSession | null = null;
|
|
110
|
+
const leads: FleetLead[] = [];
|
|
111
|
+
for (const row of roles.rows) {
|
|
112
|
+
if (/^relay$/i.test(row.role)) { relay = take(row.sessionId); continue; }
|
|
113
|
+
let session = take(row.sessionId);
|
|
114
|
+
// roles.md is hand-edited and runs behind: when the listed id is not live, a live session named for the role stands in
|
|
115
|
+
if (!session && row.role.length > 3) {
|
|
116
|
+
const named = sessions.find((s) => !used.has(s.id) && s.status === 'live' && s.name.toLowerCase().startsWith(row.role.toLowerCase()));
|
|
117
|
+
if (named) { used.add(named.id); session = named; }
|
|
118
|
+
}
|
|
119
|
+
leads.push({ role: row.role, notes: row.notes, listedId: row.sessionId && session?.id !== row.sessionId ? row.sessionId : undefined, session, children: row.childIds.map((id) => take(id)).filter((s): s is FleetSession => !!s) });
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
relay, leads, others: sessions.filter((s) => !used.has(s.id)),
|
|
123
|
+
waitingOnQuinn: loops.waitingOnQuinn, waitingOnSessions: loops.waitingOnSessions,
|
|
124
|
+
rolesUpdated: roles.updated, loopsUpdated: loops.updated, ports, sections: loops.sections, unparsed: [...roles.unparsed, ...loops.unparsed],
|
|
125
|
+
};
|
|
126
|
+
}
|
|
@@ -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
|
|
14
|
+
export const MAX_FLEET_INPUT = 200000;
|
|
15
|
+
export interface FleetSnapshot { text: string; updatedAt: string; inputs?: FleetInputs }
|
|
14
16
|
|
|
15
|
-
|
|
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,
|
|
26
|
-
function filedText(
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
const
|
|
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 ${
|
|
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
|
-
|
|
140
|
-
|
|
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
|
-
|
|
217
|
-
|
|
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<
|
|
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))
|
|
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.
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
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)
|
|
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)
|
|
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 {
|