@startsimpli/integrations 0.2.160 → 0.2.163

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 (54) hide show
  1. package/package.json +6 -6
  2. package/src/__tests__/converse-brain.test.ts +84 -0
  3. package/src/__tests__/converse-client.test.ts +39 -0
  4. package/src/__tests__/converse-config.test.ts +9 -0
  5. package/src/__tests__/converse-extract.test.ts +19 -0
  6. package/src/__tests__/converse-page.test.tsx +104 -0
  7. package/src/__tests__/converse.test.ts +212 -0
  8. package/src/__tests__/corpus-planning.test.tsx +31 -0
  9. package/src/__tests__/measure/notes.ts +28 -0
  10. package/src/__tests__/measure/voice-notes.measure.test.ts +51 -0
  11. package/src/__tests__/question-evidence.test.ts +82 -0
  12. package/src/__tests__/question-voice.test.ts +18 -0
  13. package/src/components/index.ts +2 -0
  14. package/src/components/pages/ConversePage.tsx +184 -0
  15. package/src/components/pages/PlanningPage.tsx +14 -4
  16. package/src/components/pages/converse/silence.ts +20 -0
  17. package/src/components/pages/converse/useRecorder.ts +55 -0
  18. package/src/corpus/converse/brain.ts +84 -0
  19. package/src/corpus/converse/client.ts +64 -0
  20. package/src/corpus/converse/config.ts +21 -0
  21. package/src/corpus/converse/extract.ts +41 -0
  22. package/src/corpus/converse/handle.ts +147 -0
  23. package/src/corpus/converse/index.ts +16 -0
  24. package/src/corpus/converse/respond.ts +88 -0
  25. package/src/corpus/converse/store.ts +74 -0
  26. package/src/corpus/converse/transcript.ts +20 -0
  27. package/src/corpus/converse/types.ts +133 -0
  28. package/src/corpus/index.ts +1 -0
  29. package/src/corpus/llm.ts +3 -2
  30. package/src/corpus/questions/evidence.ts +65 -0
  31. package/src/corpus/questions/index.ts +4 -1
  32. package/src/corpus/questions/items.ts +21 -0
  33. package/src/corpus/questions/learn.ts +16 -0
  34. package/src/corpus/questions/sync.ts +7 -3
  35. package/src/corpus/questions/types.ts +3 -1
  36. package/src/corpus/questions/voice.ts +23 -4
  37. package/src/corpus/voice.ts +5 -2
  38. package/src/native/app/FoundryApp.tsx +2 -2
  39. package/src/native/app/__tests__/launch.test.ts +1 -1
  40. package/src/native/app/config/defaults.ts +3 -2
  41. package/src/native/app/config/types.ts +3 -1
  42. package/src/native/app/converseServices.ts +46 -0
  43. package/src/native/app/launch.ts +4 -0
  44. package/src/native/app/registry.tsx +8 -0
  45. package/src/native/app/services.ts +5 -2
  46. package/src/native/converse/ConverseScreen.tsx +70 -0
  47. package/src/native/converse/__tests__/controller.test.ts +182 -0
  48. package/src/native/converse/api.ts +81 -0
  49. package/src/native/converse/controller.ts +252 -0
  50. package/src/native/converse/fake.ts +34 -0
  51. package/src/native/converse/format.ts +25 -0
  52. package/src/native/converse/index.ts +8 -0
  53. package/src/native/converse/tab.tsx +14 -0
  54. package/src/native/index.ts +1 -0
@@ -0,0 +1,147 @@
1
+ /**
2
+ * handleConverseTurn: one thing said -> understood -> answered -> spoken back -> KEPT.
3
+ *
4
+ * find or start the caller's conversation -> [replay? answer from the record] -> words (transcribe if audio)
5
+ * -> brain (history + words) -> speak -> save both recordings and the turn.
6
+ *
7
+ * The record is saved on every turn. A failure in the brain or in speech never loses the turn: the person
8
+ * gets a sentence saying so and the conversation goes on. Request-free so a Next route, a worker and a test
9
+ * all call the same thing.
10
+ */
11
+ import { renderTranscript, titleFor } from './transcript';
12
+ import { createEntityConversationStore } from './store';
13
+ import {
14
+ CLIENT_ID, ConverseError, MAX_CONVERSE_AUDIO_BYTES, turnAudioPath,
15
+ type ConversationRecord, type ConverseDeps, type ConverseEndResult, type ConverseSide, type ConverseTurn, type ConverseTurnRequest, type ConverseTurnResult,
16
+ } from './types';
17
+
18
+ const DEFAULT_HISTORY_LINES = 24;
19
+ const NOT_HEARD = 'Sorry, I did not catch that. Can you say that again?';
20
+ const BRAIN_FAILED = 'I am having trouble thinking right now. Your words are saved. Try again in a moment.';
21
+
22
+ const resultOf = (id: string, turn: ConverseTurn): ConverseTurnResult => ({
23
+ conversation_id: id,
24
+ turn_id: turn.turn_id,
25
+ turn: turn.n,
26
+ transcript: turn.user.text,
27
+ reply_text: turn.assistant.text,
28
+ audio_url: turn.assistant.audio_ref ? turnAudioPath(id, turn.n) : null,
29
+ });
30
+
31
+ function validate(req: ConverseTurnRequest) {
32
+ if (req.conversationId !== undefined && !CLIENT_ID.test(req.conversationId)) throw new ConverseError('That conversation id is not valid.', 400);
33
+ if (req.turnId !== undefined && !CLIENT_ID.test(req.turnId)) throw new ConverseError('turn_id must be 8-64 letters, digits, - or _.', 400);
34
+ if (!req.text?.trim() && !req.audio) throw new ConverseError('Send what was said: audio or text.', 400);
35
+ if (req.audio && req.audio.audio.byteLength > MAX_CONVERSE_AUDIO_BYTES) throw new ConverseError('That recording is too long for one turn.', 413);
36
+ }
37
+
38
+ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRequest): Promise<ConverseTurnResult> {
39
+ validate(req);
40
+ const now = (deps.now ?? Date.now)();
41
+ const store = deps.store ?? createEntityConversationStore(deps.http, deps.ownerSub);
42
+ const newId = deps.newId ?? (() => crypto.randomUUID());
43
+
44
+ let record: ConversationRecord | null = null;
45
+ if (req.conversationId) {
46
+ record = await store.get(req.conversationId);
47
+ if (!record) throw new ConverseError('Not found.', 404);
48
+ if (record.status === 'ended') throw new ConverseError('That conversation has ended. Start a new one.', 409, 'ended');
49
+ }
50
+ const conversationId = record?.conversationId ?? newId();
51
+ if (!CLIENT_ID.test(conversationId)) throw new ConverseError('Could not start a conversation.', 500);
52
+
53
+ // Replay: a phone that lost the 200 sends the same press again. Nothing runs twice.
54
+ const again = req.turnId ? record?.turns.find((t) => t.turn_id === req.turnId) : undefined;
55
+ if (again) return resultOf(conversationId, again);
56
+
57
+ const n = (record?.turns.length ?? 0) + 1;
58
+ const turnId = req.turnId ?? `t${n}-${newId()}`.slice(0, 64).replace(/[^A-Za-z0-9_-]/g, '_').padEnd(8, '_');
59
+ const timeZone = req.timeZone || record?.timeZone || 'UTC';
60
+ const hints = (record?.turns ?? []).slice(-3).map((t) => t.user.text);
61
+
62
+ // 1. Words.
63
+ let utterance = req.text?.trim() ?? '';
64
+ if (req.audio) {
65
+ if (!deps.transcribe) throw new ConverseError('Speech to text is not set up.', 503, 'transcription_unavailable');
66
+ try {
67
+ utterance = (await deps.transcribe({ audio: req.audio.audio, mimeType: req.audio.mimeType, hints })).trim();
68
+ } catch (error) {
69
+ throw new ConverseError(`I could not make out the recording: ${error instanceof Error ? error.message : 'transcription failed'}`, 502, 'transcription_failed');
70
+ }
71
+ }
72
+
73
+ // 2. Answer.
74
+ let replyText = NOT_HEARD;
75
+ let did: string[] | undefined;
76
+ if (utterance) {
77
+ const lines = (record?.turns ?? []).flatMap((t) => [{ role: 'user' as const, text: t.user.text }, { role: 'assistant' as const, text: t.assistant.text }]);
78
+ const history = lines.slice(-(deps.historyLines ?? DEFAULT_HISTORY_LINES));
79
+ try {
80
+ const out = await deps.brain({ utterance, history, timeZone, now });
81
+ replyText = out.text.trim() || NOT_HEARD;
82
+ did = out.did?.length ? out.did : undefined;
83
+ } catch (error) {
84
+ console.error('[converse] brain failed (turn kept)', error);
85
+ replyText = BRAIN_FAILED;
86
+ }
87
+ }
88
+
89
+ // 3. Keep both recordings; speak the reply. Neither is allowed to lose the turn.
90
+ const user: ConverseSide = { text: utterance };
91
+ if (req.audio && deps.audio) {
92
+ try {
93
+ user.audio_ref = await deps.audio.put({ noteId: `${conversationId}-t${n}-user`, audio: req.audio.audio, mimeType: req.audio.mimeType });
94
+ user.audio_mime = req.audio.mimeType;
95
+ } catch (error) {
96
+ user.audio_reason = error instanceof Error ? error.message : String(error);
97
+ }
98
+ }
99
+ const assistant: ConverseSide = { text: replyText };
100
+ if (!deps.synthesize || !deps.audio) assistant.audio_reason = 'speech is not configured';
101
+ else {
102
+ try {
103
+ const spoken = await deps.synthesize({ text: replyText });
104
+ assistant.audio_ref = await deps.audio.put({ noteId: `${conversationId}-t${n}-reply`, audio: spoken.audio, mimeType: spoken.mimeType });
105
+ assistant.audio_mime = spoken.mimeType;
106
+ } catch (error) {
107
+ assistant.audio_reason = error instanceof Error ? error.message : String(error);
108
+ }
109
+ }
110
+
111
+ // 4. Save.
112
+ const turn: ConverseTurn = { n, turn_id: turnId, at: new Date(now).toISOString(), user, assistant, ...(did ? { did } : {}) };
113
+ const startedAt = record?.startedAt ?? turn.at;
114
+ await store.save({
115
+ ...(record ?? { status: 'open' as const, conversationId, externalId: '' }),
116
+ conversationId, startedAt, status: 'open',
117
+ ...(req.timeZone || record?.timeZone ? { timeZone } : {}),
118
+ title: record?.title || titleFor(startedAt, utterance),
119
+ turns: [...(record?.turns ?? []), turn],
120
+ });
121
+ return resultOf(conversationId, turn);
122
+ }
123
+
124
+ /** End: finish the record, write the transcript as its document body, pull out asks and decisions. Idempotent. */
125
+ export async function handleConverseEnd(deps: ConverseDeps, req: { conversationId: string }): Promise<ConverseEndResult> {
126
+ if (!CLIENT_ID.test(req.conversationId ?? '')) throw new ConverseError('Say which conversation to end.', 400);
127
+ const store = deps.store ?? createEntityConversationStore(deps.http, deps.ownerSub);
128
+ const record = await store.get(req.conversationId);
129
+ if (!record) throw new ConverseError('Not found.', 404);
130
+ const done = (r: ConversationRecord): ConverseEndResult => ({
131
+ saved: true, conversation_id: r.conversationId, record_id: r.id, turns: r.turns.length, asks: r.asks ?? [], decisions: r.decisions ?? [],
132
+ });
133
+ if (record.status === 'ended') return done(record);
134
+
135
+ const base = { ...record, status: 'ended' as const, endedAt: new Date((deps.now ?? Date.now)()).toISOString() };
136
+ let asks: string[] = [];
137
+ let decisions: string[] = [];
138
+ if (deps.extract && record.turns.length) {
139
+ try {
140
+ ({ asks, decisions } = await deps.extract({ transcript: renderTranscript(base) }));
141
+ } catch (error) {
142
+ console.error('[converse] extraction failed (conversation kept)', error);
143
+ }
144
+ }
145
+ const withAsks = { ...base, asks, decisions };
146
+ return done(await store.save({ ...withAsks, body: renderTranscript(withAsks) }));
147
+ }
@@ -0,0 +1,16 @@
1
+ export { handleConverseTurn, handleConverseEnd } from './handle';
2
+ export { converseResponse, converseEndResponse, converseAudioResponse } from './respond';
3
+ export { createEntityConversationStore, conversationExternalId } from './store';
4
+ export { renderTranscript, titleFor } from './transcript';
5
+ export { ConverseError, CONVERSATION_SOURCE, turnAudioPath } from './types';
6
+ export type {
7
+ ConversationRecord, ConversationStore, ConverseBrain, ConverseBrainInput, ConverseBrainOutput, ConverseDeps, ConverseEndResult,
8
+ ConverseTurn, ConverseTurnRequest, ConverseTurnResult, HistoryLine,
9
+ } from './types';
10
+ export { createConverseBrain, questionWithHistory, speakableAnswer } from './brain';
11
+ export type { ConverseBrainDeps } from './brain';
12
+ export { createConverseClient, ConverseClientError } from './client';
13
+ export type { ConverseClient } from './client';
14
+ export { converseEnv } from './config';
15
+ export { createConverseExtractor, parseExtract } from './extract';
16
+ export type { ConverseExtract } from './extract';
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Fetch-`Response` wrappers for the tenant frontend's route files:
3
+ * POST /corpus/converse multipart (audio | text, conversation_id, timeZone, turn_id) or JSON
4
+ * POST /corpus/converse/end JSON {conversation_id}
5
+ * GET /corpus/converse/<id>/turn/<n>/audio[?who=user] a turn's recording, to its owner only
6
+ */
7
+ import { isTimeZone } from '../spoken-time';
8
+ import { voiceErrorResponse } from '../voice-manage';
9
+ import { handleConverseEnd, handleConverseTurn } from './handle';
10
+ import { createEntityConversationStore } from './store';
11
+ import { CLIENT_ID, ConverseError, MAX_CONVERSE_AUDIO_BYTES, type ConverseDeps, type ConverseTurnRequest } from './types';
12
+
13
+ const str = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() ? v.trim() : undefined);
14
+
15
+ async function fieldsOf(request: Request): Promise<{ fields: Record<string, unknown>; audio?: ConverseTurnRequest['audio'] }> {
16
+ const type = request.headers.get('content-type') ?? '';
17
+ if (type.includes('multipart/form-data')) {
18
+ const form = (await request.formData().catch(() => { throw new ConverseError('Send multipart form data or JSON.', 400); })) as unknown as {
19
+ entries(): Iterable<[string, unknown]>;
20
+ get(name: string): unknown;
21
+ };
22
+ const fields = Object.fromEntries([...form.entries()].filter(([, v]) => typeof v === 'string'));
23
+ const file = form.get('audio');
24
+ if (file instanceof Blob && file.size > 0) {
25
+ if (file.size > MAX_CONVERSE_AUDIO_BYTES) throw new ConverseError('That recording is too long for one turn.', 413);
26
+ return { fields, audio: { audio: new Uint8Array(await file.arrayBuffer()), mimeType: file.type || 'audio/mp4' } };
27
+ }
28
+ return { fields };
29
+ }
30
+ try {
31
+ const fields = JSON.parse((await request.text()) || '{}');
32
+ if (!fields || typeof fields !== 'object') throw new Error('shape');
33
+ return { fields };
34
+ } catch {
35
+ throw new ConverseError('Send JSON, or multipart with the recording.', 400);
36
+ }
37
+ }
38
+
39
+ const failure = (error: unknown) =>
40
+ error instanceof ConverseError
41
+ ? Response.json({ detail: error.message, ...(error.code ? { code: error.code } : {}) }, { status: error.status })
42
+ : voiceErrorResponse(error);
43
+
44
+ export async function converseResponse(request: Request, deps: ConverseDeps): Promise<Response> {
45
+ try {
46
+ const { fields, audio } = await fieldsOf(request);
47
+ const zone = str(fields.timeZone);
48
+ return Response.json(await handleConverseTurn(deps, {
49
+ conversationId: str(fields.conversation_id ?? fields.conversationId),
50
+ turnId: str(fields.turn_id ?? fields.turnId),
51
+ ...(str(fields.text) ? { text: str(fields.text) } : {}),
52
+ ...(audio ? { audio } : {}),
53
+ ...(zone && isTimeZone(zone) ? { timeZone: zone } : {}),
54
+ }));
55
+ } catch (error) {
56
+ return failure(error);
57
+ }
58
+ }
59
+
60
+ export async function converseEndResponse(request: Request, deps: ConverseDeps): Promise<Response> {
61
+ try {
62
+ const { fields } = await fieldsOf(request);
63
+ return Response.json(await handleConverseEnd(deps, { conversationId: str(fields.conversation_id ?? fields.conversationId) ?? '' }));
64
+ } catch (error) {
65
+ return failure(error);
66
+ }
67
+ }
68
+
69
+ /** A turn's recording. The conversation is read as the caller, so anyone else's id is a 404. */
70
+ export async function converseAudioResponse(
71
+ conversationId: string,
72
+ n: number,
73
+ who: 'user' | 'reply',
74
+ deps: Pick<ConverseDeps, 'http' | 'ownerSub' | 'store'> & { audio?: ConverseDeps['audio'] },
75
+ ): Promise<Response> {
76
+ const notFound = () => Response.json({ detail: 'Not found.' }, { status: 404 });
77
+ if (!CLIENT_ID.test(conversationId) || !Number.isInteger(n) || n < 1 || !deps.audio) return notFound();
78
+ try {
79
+ const store = deps.store ?? createEntityConversationStore(deps.http, deps.ownerSub);
80
+ const turn = (await store.get(conversationId))?.turns.find((t) => t.n === n);
81
+ const ref = who === 'user' ? turn?.user.audio_ref : turn?.assistant.audio_ref;
82
+ if (!ref) return notFound();
83
+ const { audio, mimeType } = await deps.audio.get(ref);
84
+ return new Response(audio as BodyInit, { headers: { 'content-type': mimeType, 'cache-control': 'private, max-age=300', 'content-length': String(audio.byteLength) } });
85
+ } catch (error) {
86
+ return failure(error);
87
+ }
88
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Where a conversation is kept: ONE tenant row per conversation, keyed `conversation:<id>:<owner>`.
3
+ *
4
+ * A generic `source_document` with source `conversation` (CLAUDE.md rule 5: no new table). It carries NO
5
+ * `body` while it is open, so nothing can mistake a half-finished talk for a finished document; End
6
+ * writes the transcript into `body`. Owner scope is checked HERE as well as by the tenant: the lookup key
7
+ * carries the owner and a row whose `owner_sub` is not the caller's is treated as absent.
8
+ */
9
+ import type { TenantEntity } from '../entities';
10
+ import { CONVERSATION_SOURCE, type ConversationRecord, type ConversationStore, type ConverseDeps, type ConverseTurn } from './types';
11
+
12
+ export const conversationExternalId = (conversationId: string, ownerSub: string) => `conversation:${conversationId}:${ownerSub}`;
13
+
14
+ const text = (v: unknown) => (typeof v === 'string' ? v : '');
15
+ const list = (v: unknown): string[] => (Array.isArray(v) ? v.map(String) : []);
16
+
17
+ function toRecord(entity: TenantEntity): ConversationRecord {
18
+ const d = (entity.data ?? {}) as Record<string, unknown>;
19
+ return {
20
+ id: String(entity.id),
21
+ conversationId: text(d.conversation_id),
22
+ externalId: text(entity.external_id ?? entity.externalId),
23
+ status: d.status === 'ended' ? 'ended' : 'open',
24
+ startedAt: text(d.started_at),
25
+ ...(d.ended_at ? { endedAt: text(d.ended_at) } : {}),
26
+ ...(d.time_zone ? { timeZone: text(d.time_zone) } : {}),
27
+ title: text(d.title),
28
+ turns: Array.isArray(d.turns) ? (d.turns as ConverseTurn[]) : [],
29
+ ...(d.body ? { body: text(d.body) } : {}),
30
+ ...(d.asks ? { asks: list(d.asks) } : {}),
31
+ ...(d.decisions ? { decisions: list(d.decisions) } : {}),
32
+ };
33
+ }
34
+
35
+ export function createEntityConversationStore(http: ConverseDeps['http'], ownerSub: string): ConversationStore {
36
+ return {
37
+ async get(conversationId) {
38
+ const externalId = conversationExternalId(conversationId, ownerSub);
39
+ const page = await http.get<{ results?: TenantEntity[] }>('api/v1/entities', {
40
+ params: { type: 'source_document', external_id__in: externalId, page_size: 5 },
41
+ });
42
+ const hit = (page.results ?? []).find((r) => {
43
+ const data = (r.data ?? {}) as Record<string, unknown>;
44
+ return (r.external_id ?? r.externalId) === externalId && data.owner_sub === ownerSub && data.source === CONVERSATION_SOURCE;
45
+ });
46
+ return hit ? toRecord(hit) : null;
47
+ },
48
+ async save(record) {
49
+ const row = await http.post<TenantEntity>('api/v1/entities/upsert', {
50
+ entity_type: 'source_document',
51
+ external_id: conversationExternalId(record.conversationId, ownerSub),
52
+ name: record.title,
53
+ data: {
54
+ title: record.title,
55
+ source: CONVERSATION_SOURCE,
56
+ source_label: 'Conversation',
57
+ source_ref: conversationExternalId(record.conversationId, ownerSub),
58
+ occurred_at: record.startedAt,
59
+ owner_sub: ownerSub,
60
+ conversation_id: record.conversationId,
61
+ status: record.status,
62
+ started_at: record.startedAt,
63
+ ended_at: record.endedAt ?? '',
64
+ time_zone: record.timeZone ?? '',
65
+ turns: record.turns,
66
+ ...(record.body !== undefined ? { body: record.body } : {}),
67
+ ...(record.asks ? { asks: record.asks } : {}),
68
+ ...(record.decisions ? { decisions: record.decisions } : {}),
69
+ },
70
+ });
71
+ return { ...record, id: String(row.id) };
72
+ },
73
+ };
74
+ }
@@ -0,0 +1,20 @@
1
+ /** A conversation as a document: what is saved as the record's `body` at End. Pure. */
2
+ import type { ConversationRecord } from './types';
3
+
4
+ export function renderTranscript(record: Pick<ConversationRecord, 'turns' | 'startedAt' | 'timeZone' | 'asks' | 'decisions'>): string {
5
+ const lines: string[] = [];
6
+ if (record.asks?.length) lines.push('## Asks', ...record.asks.map((a) => `- ${a}`), '');
7
+ if (record.decisions?.length) lines.push('## Decisions', ...record.decisions.map((d) => `- ${d}`), '');
8
+ lines.push('## Transcript');
9
+ for (const turn of record.turns) {
10
+ lines.push('', `**You:** ${turn.user.text}`, '', `**Tandem:** ${turn.assistant.text}`);
11
+ if (turn.did?.length) lines.push('', ...turn.did.map((d) => `_${d}_`));
12
+ }
13
+ return lines.join('\n').trim();
14
+ }
15
+
16
+ export function titleFor(startedAt: string, firstWords: string): string {
17
+ const day = startedAt.slice(0, 10);
18
+ const words = firstWords.replace(/\s+/g, ' ').trim().split(' ').slice(0, 7).join(' ');
19
+ return words ? `Conversation ${day}: ${words}` : `Conversation ${day}`;
20
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * THE CONVERSE ENDPOINT'S SHAPES (bd startsim-wc67c, startsim-kufsm).
3
+ *
4
+ * One turn = one thing said + one thing said back. The conversation (its turns, both recordings,
5
+ * the transcript) is ONE owner-only tenant record, saved after EVERY turn: a drive ends without
6
+ * anyone pressing End, and the recording is half of what was asked to be kept.
7
+ *
8
+ * Field names on the wire are the iOS app's contract: `conversation_id` (snake), `timeZone` (camel).
9
+ */
10
+ import type { CorpusHttp } from '../client';
11
+ import type { BriefingAudio, BriefingSynthesize } from '../briefing/generate';
12
+
13
+ export type ConverseRole = 'user' | 'assistant';
14
+ export interface HistoryLine { role: ConverseRole; text: string }
15
+
16
+ export interface ConverseSide {
17
+ text: string;
18
+ audio_ref?: string;
19
+ audio_mime?: string;
20
+ /** Why there is no audio for this side, when there should have been. */
21
+ audio_reason?: string;
22
+ }
23
+
24
+ export interface ConverseTurn {
25
+ n: number;
26
+ /** The client's id for this press: sending it again replays the turn. */
27
+ turn_id: string;
28
+ at: string;
29
+ user: ConverseSide;
30
+ assistant: ConverseSide;
31
+ /** What the assistant did to the person's items this turn, in words. */
32
+ did?: string[];
33
+ }
34
+
35
+ export interface ConversationRecord {
36
+ /** Tenant row id. */
37
+ id: string;
38
+ /** The id the client holds. */
39
+ conversationId: string;
40
+ externalId: string;
41
+ status: 'open' | 'ended';
42
+ startedAt: string;
43
+ endedAt?: string;
44
+ timeZone?: string;
45
+ title: string;
46
+ turns: ConverseTurn[];
47
+ /** Set at End: the transcript as a document, and what the handoff pulled out of it. */
48
+ body?: string;
49
+ asks?: string[];
50
+ decisions?: string[];
51
+ }
52
+
53
+ export interface ConversationStore {
54
+ /** One of the caller's own conversations by the client's id; null for anyone else's or none. */
55
+ get(conversationId: string): Promise<ConversationRecord | null>;
56
+ save(record: Omit<ConversationRecord, 'id'> & { id?: string }): Promise<ConversationRecord>;
57
+ }
58
+
59
+ /** What the assistant works out for one utterance. */
60
+ export interface ConverseBrainInput {
61
+ utterance: string;
62
+ history: HistoryLine[];
63
+ timeZone: string;
64
+ now: number;
65
+ }
66
+ export interface ConverseBrainOutput {
67
+ /** What is said back. Plain sentences: it is read aloud. */
68
+ text: string;
69
+ /** What it did to items, in words (kept on the turn). */
70
+ did?: string[];
71
+ }
72
+ export type ConverseBrain = (input: ConverseBrainInput) => Promise<ConverseBrainOutput>;
73
+
74
+ export interface ConverseTurnRequest {
75
+ /** Absent on the first turn. */
76
+ conversationId?: string;
77
+ text?: string;
78
+ audio?: { audio: Uint8Array; mimeType: string };
79
+ timeZone?: string;
80
+ /** Fresh per press; optional. */
81
+ turnId?: string;
82
+ }
83
+
84
+ /** The 200 body. */
85
+ export interface ConverseTurnResult {
86
+ conversation_id: string;
87
+ turn_id: string;
88
+ turn: number;
89
+ transcript: string;
90
+ reply_text: string;
91
+ /** Owner-checked, relative to the tenant; GET with the bearer. Null when only text is available. */
92
+ audio_url: string | null;
93
+ }
94
+
95
+ export interface ConverseEndResult {
96
+ saved: true;
97
+ conversation_id: string;
98
+ /** The record's row id, for Library/MCP lookups. */
99
+ record_id: string;
100
+ turns: number;
101
+ asks: string[];
102
+ decisions: string[];
103
+ }
104
+
105
+ export interface ConverseDeps {
106
+ http: Pick<CorpusHttp, 'get'> & { post<T>(path: string, body?: unknown): Promise<T> };
107
+ ownerSub: string;
108
+ brain: ConverseBrain;
109
+ synthesize?: BriefingSynthesize;
110
+ audio?: Pick<BriefingAudio, 'put'> & { get(audioRef: string): Promise<{ audio: Uint8Array; mimeType: string }> };
111
+ transcribe?: (input: { audio: Uint8Array; mimeType: string; hints: string[] }) => Promise<string>;
112
+ /** Pulls asks and decisions out of a finished conversation. Default: none. */
113
+ extract?: (input: { transcript: string }) => Promise<{ asks: string[]; decisions: string[] }>;
114
+ store?: ConversationStore;
115
+ now?: () => number;
116
+ newId?: () => string;
117
+ /** How many earlier lines the brain sees. Default 24. */
118
+ historyLines?: number;
119
+ }
120
+
121
+ /** An error the route turns into a status; `code` lets the app choose its message. */
122
+ export class ConverseError extends Error {
123
+ constructor(message: string, readonly status: number, readonly code?: string) {
124
+ super(message);
125
+ this.name = 'ConverseError';
126
+ }
127
+ }
128
+
129
+ export const CONVERSATION_SOURCE = 'conversation';
130
+ export const MAX_CONVERSE_AUDIO_BYTES = 25 * 1024 * 1024;
131
+ export const CLIENT_ID = /^[A-Za-z0-9_-]{8,64}$/;
132
+ export const turnAudioPath = (conversationId: string, n: number, who: 'user' | 'reply' = 'reply') =>
133
+ `/corpus/converse/${encodeURIComponent(conversationId)}/turn/${n}/audio${who === 'user' ? '?who=user' : ''}`;
@@ -287,6 +287,7 @@ export { dueDay, localDate, selectToday, todayKind } from './today';
287
287
  export type { TodayEntry, TodayItem, TodayKind, TodayRule } from './today';
288
288
  // Daily briefing: what is on one person's plate today (bd startsim-kgkp1).
289
289
  export * from './briefing';
290
+ export * from './converse';
290
291
 
291
292
  // Spoken time -> due dates, and the per-field guesses extraction reports (bd startsim-b7kir).
292
293
  export { isTimeZone, noteWideWhen, resolveSpokenTime } from './spoken-time';
package/src/corpus/llm.ts CHANGED
@@ -570,7 +570,7 @@ function freshNonce(): string {
570
570
  }
571
571
 
572
572
  export function renderVoicePrompt(
573
- input: { transcript: string; focuses: FocusChoice[]; now?: number; timeZone?: string },
573
+ input: { transcript: string; focuses: FocusChoice[]; now?: number; timeZone?: string; habits?: string[] },
574
574
  nonce: () => string = freshNonce,
575
575
  ): string {
576
576
  const list = input.focuses.length
@@ -582,7 +582,8 @@ export function renderVoicePrompt(
582
582
  const code = nonce();
583
583
  if (input.transcript.includes(code)) continue;
584
584
  const recorded = input.now === undefined ? '' : `RECORDED_AT: ${recordedAtLine(input.now, input.timeZone || 'UTC')}\n\n`;
585
- return `${recorded}PROJECTS (focusId must be one of these ids, or null):\n${list}\n\nTRANSCRIPT:\n${untrustedDocument(input.transcript, code)}`;
585
+ const habits = input.habits?.length ? `HABITS (what this speaker has told us before; a hint for choosing focusId when the topic really matches, never a reason to guess):\n${input.habits.join('\n')}\n\n` : '';
586
+ return `${recorded}PROJECTS (focusId must be one of these ids, or null):\n${list}\n\n${habits}TRANSCRIPT:\n${untrustedDocument(input.transcript, code)}`;
586
587
  }
587
588
  throw new Error('Could not pick a delimiter that the transcript does not contain.');
588
589
  }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * RESOLVE FROM THE CORPUS BEFORE ASKING (bd startsim-tmrvi.2).
3
+ *
4
+ * Habits (learn.ts) come from the person's own past answers. This is the other half: evidence already in
5
+ * the workspace. Other to-dos from other notes, Linear issues (to-dos that carry a Linear key) and calendar
6
+ * events say where similar work lives and when things happen. Like a habit, evidence can only CONFIRM the
7
+ * guess Tandem is already acting on, never change it; any similar item pointing elsewhere keeps the
8
+ * question open. Pure: callers read the rows, this decides and says why.
9
+ */
10
+ import { contentWords } from '../briefing/intent/match';
11
+ import type { EvidenceEvent } from './items';
12
+ import type { ItemView, QuestionKind } from './types';
13
+
14
+ const day = (v: string | null | undefined) => (v ? String(v).slice(0, 10) : '');
15
+ const long = (title: string) => [...new Set(contentWords(title).filter((w) => w.length >= 4))];
16
+
17
+ /** How many words two titles share. */
18
+ function shared(a: string[], b: string[]): string[] {
19
+ const set = new Set(b);
20
+ return a.filter((w) => set.has(w));
21
+ }
22
+
23
+ const label = (i: ItemView) => (i.linearKey ? `Linear ${i.linearKey}` : `"${i.title}"`);
24
+
25
+ /** Similar = at least two content words in common (one word is too loose to act on). */
26
+ function similarTo(item: ItemView, others: ItemView[]): ItemView[] {
27
+ const words = long(item.title);
28
+ if (words.length === 0) return [];
29
+ return others.filter((o) => o.id !== item.id && shared(words, long(o.title)).length >= 2);
30
+ }
31
+
32
+ export interface ContextHit { agrees: true; evidence: string; source: 'items' | 'linear' | 'calendar' }
33
+
34
+ export function decideFromCorpus(
35
+ input: { kind: QuestionKind; item: ItemView; assumed?: { value: string | null } },
36
+ corpus: { items: ItemView[]; events: EvidenceEvent[] },
37
+ ): ContextHit | null {
38
+ const assumed = input.assumed?.value;
39
+ if (!assumed) return null;
40
+ const { item } = input;
41
+
42
+ if (input.kind === 'project') {
43
+ const like = similarTo(item, corpus.items).filter((o) => o.focusId);
44
+ if (like.length < 2) return null;
45
+ if (like.some((o) => o.focusId !== assumed)) return null; // a similar item lives elsewhere: ask
46
+ const linear = like.some((o) => o.linearKey);
47
+ return {
48
+ agrees: true, source: linear ? 'linear' : 'items',
49
+ evidence: `${like.length} similar to-dos (${like.slice(0, 2).map(label).join(', ')}) are in the same project`,
50
+ };
51
+ }
52
+
53
+ if (input.kind === 'due_date') {
54
+ const target = day(assumed);
55
+ if (!target) return null;
56
+ const words = long(item.title);
57
+ const event = corpus.events.find((e) => e.date === target && shared(words, long(e.title)).length >= 1);
58
+ if (event) return { agrees: true, source: 'calendar', evidence: `calendar: "${event.title}" on ${target}` };
59
+ const linked = similarTo(item, corpus.items).filter((o) => o.linearKey && o.dueAt);
60
+ if (linked.length > 0 && linked.every((o) => day(o.dueAt) === target)) {
61
+ return { agrees: true, source: 'linear', evidence: `${label(linked[0] as ItemView)} is due ${target}` };
62
+ }
63
+ }
64
+ return null;
65
+ }
@@ -21,7 +21,10 @@ export { composeCheckIn } from './checkin';
21
21
  export type { CheckIn, CheckInEntry, CheckInOptions } from './checkin';
22
22
  export { buildCheckIn } from './checkin-handle';
23
23
  export type { CheckInResult } from './checkin-handle';
24
- export { createPreferenceStore, learnFromAnswer, nextEvidence, decideFromHabits, PREFERENCE_ATTRIBUTES, PREFERENCE_LABEL, PREFERENCE_TYPE } from './learn';
24
+ export { decideFromCorpus } from './evidence';
25
+ export type { ContextHit } from './evidence';
26
+ export type { EvidenceEvent } from './items';
27
+ export { createPreferenceStore, learnFromAnswer, nextEvidence, decideFromHabits, habitHints, PREFERENCE_ATTRIBUTES, PREFERENCE_LABEL, PREFERENCE_TYPE } from './learn';
25
28
  export type { Preference, PreferenceKind } from './learn';
26
29
  export { applyAnswerToItem, assumedLabel, chipsFor, formatAnswerValue, readTypedAnswer } from './inbox';
27
30
  export type { AnswerChip, AnswerableItem, ChipContext, TypedAnswer } from './inbox';
@@ -9,6 +9,26 @@ const PAGE_SIZE = 200;
9
9
  const MAX_PAGES = 100;
10
10
  const str = (v: unknown): string => (typeof v === 'string' ? v : '');
11
11
 
12
+ /** A dated calendar entry; read tolerantly because tenants model them under different keys. */
13
+ export interface EvidenceEvent { title: string; date: string }
14
+ export const CALENDAR_EVENT_TYPE = 'calendar_event';
15
+
16
+ export async function readEvidenceEvents(http: CorpusHttp, entitiesPath: string, type = CALENDAR_EVENT_TYPE): Promise<EvidenceEvent[]> {
17
+ const out: EvidenceEvent[] = [];
18
+ for (let page = 1; page <= 20; page += 1) {
19
+ const res = await http.get<{ results?: TenantEntity[]; next?: string | null }>(entitiesPath, { params: { type, page, page_size: PAGE_SIZE } });
20
+ const rows = res.results ?? [];
21
+ for (const row of rows) {
22
+ const d = (row.data ?? {}) as Record<string, unknown>;
23
+ const date = str(d.start ?? d.starts_at ?? d.startsAt ?? d.date ?? d.start_date).slice(0, 10);
24
+ const title = str(d.title ?? d.summary ?? d.name ?? row.name);
25
+ if (date && title) out.push({ title, date });
26
+ }
27
+ if (!res.next || rows.length === 0) break;
28
+ }
29
+ return out;
30
+ }
31
+
12
32
  export async function readItemViews(http: CorpusHttp, scope: CorpusScope, entitiesPath: string): Promise<ItemView[]> {
13
33
  const out: ItemView[] = [];
14
34
  for (let page = 1; page <= MAX_PAGES; page += 1) {
@@ -24,6 +44,7 @@ export async function readItemViews(http: CorpusHttp, scope: CorpusScope, entiti
24
44
  id: c.id, title: c.title, status: c.status, dueAt: c.dueAt ?? null,
25
45
  focusId: str(d.external_focus_id ?? d.externalFocusId), ownerName: c.ownerName ?? '', ownerSub: c.ownerSub ?? '',
26
46
  ...(noteId ? { noteId } : {}),
47
+ ...(c.sync?.key ? { linearKey: c.sync.key } : {}),
27
48
  openKind: str(d.open_question_kind ?? d.openQuestionKind),
28
49
  openText: str(d.open_question ?? d.openQuestion),
29
50
  });
@@ -133,3 +133,19 @@ export function decideFromHabits(
133
133
  }
134
134
  return null;
135
135
  }
136
+
137
+ /**
138
+ * Project habits as hints for the extraction prompt (bd startsim-tmrvi.18). Only confident ones, only for
139
+ * projects that still exist, and only as a hint: the model still chooses by what the section is about, and
140
+ * a habit never makes a project "stated".
141
+ */
142
+ export function habitHints(prefs: Preference[], focuses: Array<{ id: string; title: string }>): string[] {
143
+ const byId = new Map(focuses.map((f) => [f.id, f.title]));
144
+ const grouped = new Map<string, string[]>();
145
+ for (const p of prefs) {
146
+ if (p.kind !== 'project_word' || !confidentIn(prefs, 'project_word', p.key)) continue;
147
+ if (!byId.has(p.value)) continue;
148
+ grouped.set(p.value, [...(grouped.get(p.value) ?? []), p.key]);
149
+ }
150
+ return [...grouped].slice(0, 10).map(([id, words]) => `- to-dos about ${words.slice(0, 8).join(', ')} usually go to ${id} (${byId.get(id)})`);
151
+ }