@startsimpli/integrations 0.2.145 → 0.2.146

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 (72) hide show
  1. package/package.json +4 -4
  2. package/src/__tests__/briefing-actions.test.ts +2 -0
  3. package/src/__tests__/briefing-reply.test.ts +334 -0
  4. package/src/__tests__/corpus-tracker.test.tsx +79 -0
  5. package/src/__tests__/owner-backfill.test.ts +114 -0
  6. package/src/__tests__/owner-link.test.ts +115 -0
  7. package/src/__tests__/owner-picker.test.tsx +70 -0
  8. package/src/__tests__/roster.test.ts +27 -0
  9. package/src/__tests__/tracker-sort.test.ts +28 -0
  10. package/src/components/index.ts +1 -0
  11. package/src/components/pages/TaskDetailPage.tsx +33 -2
  12. package/src/components/pages/TrackerPage.tsx +28 -6
  13. package/src/components/pages/task-tracker/OwnerPicker.tsx +82 -0
  14. package/src/components/pages/tracker/TrackerBoard.tsx +45 -0
  15. package/src/components/pages/tracker/TrackerToolbar.tsx +44 -0
  16. package/src/corpus/briefing/actions/execute.ts +5 -4
  17. package/src/corpus/briefing/actions/log.ts +1 -1
  18. package/src/corpus/briefing/actions/types.ts +21 -0
  19. package/src/corpus/briefing/index.ts +1 -0
  20. package/src/corpus/briefing/intent/model.ts +3 -0
  21. package/src/corpus/briefing/intent/resolve.ts +14 -6
  22. package/src/corpus/briefing/intent/types.ts +7 -0
  23. package/src/corpus/briefing/reply/handle.ts +174 -0
  24. package/src/corpus/briefing/reply/index.ts +6 -0
  25. package/src/corpus/briefing/reply/respond.ts +95 -0
  26. package/src/corpus/briefing/reply/types.ts +112 -0
  27. package/src/corpus/briefing/store.ts +14 -0
  28. package/src/corpus/client.ts +16 -18
  29. package/src/corpus/entities.ts +4 -0
  30. package/src/corpus/index.ts +4 -0
  31. package/src/corpus/owner-backfill.ts +200 -0
  32. package/src/corpus/owner-link.ts +160 -0
  33. package/src/corpus/roster.ts +53 -0
  34. package/src/corpus/tracker-groups.ts +8 -4
  35. package/src/corpus/tracker-sort.ts +51 -0
  36. package/src/corpus/types.ts +13 -1
  37. package/src/native/app/FoundryApp.tsx +25 -7
  38. package/src/native/app/__tests__/briefingLink.test.tsx +57 -0
  39. package/src/native/app/__tests__/briefingServices.test.ts +92 -0
  40. package/src/native/app/__tests__/launch.test.ts +2 -1
  41. package/src/native/app/briefingServices.ts +101 -0
  42. package/src/native/app/config/__tests__/briefingConfig.test.ts +49 -0
  43. package/src/native/app/config/links.ts +4 -1
  44. package/src/native/app/config/types.ts +13 -1
  45. package/src/native/app/config/validate.ts +20 -2
  46. package/src/native/app/data.ts +3 -3
  47. package/src/native/app/device.ts +3 -0
  48. package/src/native/app/launch.ts +4 -0
  49. package/src/native/app/registry.tsx +3 -1
  50. package/src/native/app/screens/RecordScreen.tsx +3 -2
  51. package/src/native/app/services.ts +11 -30
  52. package/src/native/app/strings.ts +28 -0
  53. package/src/native/briefing/BriefingCard.tsx +14 -2
  54. package/src/native/briefing/BriefingReply.tsx +68 -0
  55. package/src/native/briefing/__tests__/BriefingReply.test.tsx +144 -0
  56. package/src/native/briefing/__tests__/fakeReply.test.ts +46 -0
  57. package/src/native/briefing/__tests__/notify.test.ts +42 -1
  58. package/src/native/briefing/__tests__/replyApi.test.ts +43 -0
  59. package/src/native/briefing/__tests__/replyController.test.ts +230 -0
  60. package/src/native/briefing/__tests__/replyPosition.test.ts +116 -0
  61. package/src/native/briefing/audioPlayer.ts +9 -2
  62. package/src/native/briefing/controller.ts +50 -5
  63. package/src/native/briefing/fake.ts +25 -18
  64. package/src/native/briefing/fakeReply.ts +65 -0
  65. package/src/native/briefing/index.ts +8 -3
  66. package/src/native/briefing/notify.ts +42 -0
  67. package/src/native/briefing/reply.ts +261 -0
  68. package/src/native/briefing/replyApi.ts +82 -0
  69. package/src/native/recording/__tests__/deeplink.test.ts +20 -0
  70. package/src/native/recording/deeplink.ts +7 -0
  71. package/src/native/tracker/__tests__/itemsChanged.test.ts +13 -0
  72. package/src/native/tracker/tab.tsx +4 -1
@@ -7,6 +7,7 @@
7
7
  * executor changes. Keep this the ONLY way an action touches an item.
8
8
  */
9
9
  import type { Commitment } from '../../types';
10
+ import type { VoiceAction } from '../intent/types';
10
11
 
11
12
  /** What an edit needs to know about an item; a `Commitment` satisfies it. */
12
13
  export interface EditableItem {
@@ -48,6 +49,8 @@ export interface ActionResult {
48
49
  /** What was said back for this action. */
49
50
  spoken: string;
50
51
  itemId?: string;
52
+ /** Why a write failed, for logs and the app's diagnostics. Never spoken. */
53
+ reason?: string;
51
54
  }
52
55
 
53
56
  /** One undoable change: the fields before and after, to restore and to check nothing moved since. */
@@ -61,6 +64,22 @@ export interface UndoEntry {
61
64
  at: string;
62
65
  }
63
66
 
67
+ /** A reply that was understood: kept so applying it, resending it or answering its question needs no second parse. */
68
+ export interface PendingReply {
69
+ /** The client action id of the press that produced it. */
70
+ id: string;
71
+ utterance: string;
72
+ understood: string;
73
+ actions: VoiceAction[];
74
+ source: 'llm' | 'grammar';
75
+ confidence: number;
76
+ /** Set when the reply ended in a question; the next reply may answer it (`inReplyTo`). */
77
+ question?: string;
78
+ /** The spoken confirmation, served to its owner by reference. */
79
+ confirmAudio?: { ref: string; mimeType: string };
80
+ at: string;
81
+ }
82
+
64
83
  /** Everything remembered per person: what was applied (idempotency) and what can be undone. */
65
84
  export interface ActionLog {
66
85
  applied: Record<string, ActionResult>;
@@ -68,6 +87,8 @@ export interface ActionLog {
68
87
  order: string[];
69
88
  /** Newest last. */
70
89
  stack: UndoEntry[];
90
+ /** The latest replies understood, newest last (see `PendingReply`). */
91
+ pending?: PendingReply[];
71
92
  }
72
93
 
73
94
  export interface ActionLogStore {
@@ -13,3 +13,4 @@ export type { BriefingContextRecord, BriefingRecord, BriefingStore } from './sto
13
13
  export { briefingContentHash, hashString, SCRIPT_VERSION } from './cache-key';
14
14
  export * from './intent';
15
15
  export * from './actions';
16
+ export * from './reply';
@@ -58,6 +58,9 @@ export function intentPrompt(ctx: IntentContext): string {
58
58
  'Other open items (not in the briefing):',
59
59
  ...(others.length ? others.map((i) => `- ${line(i)}`) : ['(none)']),
60
60
  `Undo available: ${ctx.hasUndo ? 'yes' : 'no'}`,
61
+ ...(ctx.thread
62
+ ? [`Earlier the person said: ${JSON.stringify(ctx.thread.utterance)}`, `You asked: ${JSON.stringify(ctx.thread.question)}`, 'Their next words ANSWER that question; read the two together as one instruction.']
63
+ : []),
61
64
  `The person said: ${JSON.stringify(ctx.utterance)}`,
62
65
  ].join('\n');
63
66
  }
@@ -15,15 +15,23 @@ import type { IntentContext, IntentOptions, IntentResult } from './types';
15
15
  const DEFAULT_TIMEOUT_MS = 8_000;
16
16
  const DEFAULT_MIN_CONFIDENCE = 0.6;
17
17
 
18
- export async function resolveVoiceIntent(ctx: IntentContext, options: IntentOptions = {}): Promise<IntentResult> {
18
+ /** The plain rules' answer, with the confidence it deserves: sure when it acted, none when it only asked. */
19
+ function byGrammar(ctx: IntentContext, notes: string[]): IntentResult {
20
+ const out = parseWithGrammar(ctx);
21
+ return { ...out, confidence: out.actions.some((a) => a.type !== 'clarify' && a.type !== 'none') ? 1 : 0, notes };
22
+ }
23
+
24
+ export async function resolveVoiceIntent(asked: IntentContext, options: IntentOptions = {}): Promise<IntentResult> {
19
25
  const notes: string[] = [];
20
- if (!ctx.utterance.trim()) return { ...parseWithGrammar(ctx), notes: ['empty utterance'] };
26
+ // An answer to our question is read WITH what was said first: dates and items come from either.
27
+ const ctx: IntentContext = asked.thread ? { ...asked, utterance: `${asked.thread.utterance} ${asked.utterance}` } : asked;
28
+ if (!asked.utterance.trim()) return byGrammar(ctx, ['empty utterance']);
21
29
 
22
30
  if (options.llm) {
23
31
  try {
24
32
  const reply = await options.llm.write({
25
33
  system: intentSystemPrompt(),
26
- prompt: intentPrompt(ctx),
34
+ prompt: intentPrompt({ ...asked, utterance: asked.utterance }),
27
35
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
28
36
  });
29
37
  const checked = checkModelReply(reply, ctx);
@@ -36,14 +44,14 @@ export async function resolveVoiceIntent(ctx: IntentContext, options: IntentOpti
36
44
  notes.push('model asked; the grammar found a clear match');
37
45
  } else if (checked.confidence < (options.minConfidence ?? DEFAULT_MIN_CONFIDENCE)) {
38
46
  const actions = [{ type: 'clarify' as const, question: 'I am not sure I got that. Can you say that again?' }];
39
- return { actions, source: 'llm', understood: describeActions(actions, ctx), notes: [`low confidence ${checked.confidence}`] };
47
+ return { actions, source: 'llm', confidence: checked.confidence, understood: describeActions(actions, ctx), notes: [`low confidence ${checked.confidence}`] };
40
48
  } else {
41
- return { actions: checked.actions, source: 'llm', understood: describeActions(checked.actions, ctx), notes };
49
+ return { actions: checked.actions, source: 'llm', confidence: checked.confidence, understood: describeActions(checked.actions, ctx), notes };
42
50
  }
43
51
  }
44
52
  } catch (error) {
45
53
  notes.push(`model failed: ${error instanceof Error ? error.message : String(error)}`);
46
54
  }
47
55
  }
48
- return { ...parseWithGrammar(ctx), notes };
56
+ return byGrammar(ctx, notes);
49
57
  }
@@ -26,6 +26,11 @@ export interface IntentContext {
26
26
  readingId: string | null;
27
27
  /** Whether the undo stack has anything on it. */
28
28
  hasUndo: boolean;
29
+ /**
30
+ * Set when `utterance` ANSWERS a question this reply asked: what was said first and what was asked. The model sees
31
+ * both; the grammar and the grounding check read the two utterances as one ("move that one to Friday" + "the bench one").
32
+ */
33
+ thread?: { utterance: string; question: string };
29
34
  }
30
35
 
31
36
  export type VoiceAction =
@@ -45,6 +50,8 @@ export type VoiceAction =
45
50
  export interface IntentResult {
46
51
  actions: VoiceAction[];
47
52
  source: 'llm' | 'grammar';
53
+ /** 0..1: the model's own figure, or 1 when the plain rules acted on a named item, 0 when they only asked. */
54
+ confidence?: number;
48
55
  /** One line to show before applying: "Move Pick up printer paper to Friday". */
49
56
  understood: string;
50
57
  /** Why the model's answer was not used, for logs and the accuracy probe. */
@@ -0,0 +1,174 @@
1
+ /**
2
+ * handleBriefingReply: a spoken reply -> understood -> (previewed or applied) -> spoken back.
3
+ *
4
+ * find the caller's briefing -> [replay? answer from the log] -> words (transcribe if audio)
5
+ * -> intent (model, then plain rules) -> keep it as PENDING -> apply now (sure) or wait for `apply`
6
+ * -> executor (idempotent, undoable, through the item edit seam) -> speak the result.
7
+ *
8
+ * Request-free so a Next route, a worker and a test all call the same thing.
9
+ */
10
+ import { executeVoiceActions, speakConfirmation, type SpokenConfirmation } from '../actions';
11
+ import type { ActionLog, ActionResult, PendingReply } from '../actions/types';
12
+ import { readingAt, resolveVoiceIntent } from '../intent';
13
+ import type { IntentContext, IntentItem, IntentResult, VoiceAction } from '../intent';
14
+ import { createEntityBriefingStore, type BriefingRecord } from '../store';
15
+ import { ReplyError, type BriefingReplyDeps, type ReplyConfirmation, type ReplyRequest, type ReplyResult } from './types';
16
+
17
+ export const CLIENT_ACTION_ID = /^[A-Za-z0-9_-]{8,64}$/;
18
+ const PENDING_KEPT = 12;
19
+ const DEFAULT_MIN_AUTO = 0.85;
20
+ /** Open items offered to the transcriber as vocabulary, beyond the ones just read. */
21
+ const MAX_HINTS = 20;
22
+ export const MAX_REPLY_AUDIO_BYTES = 10 * 1024 * 1024;
23
+
24
+ export const replyAudioPath = (briefingId: string, clientActionId: string) =>
25
+ `/corpus/briefing/${encodeURIComponent(briefingId)}/reply/${encodeURIComponent(clientActionId)}/audio`;
26
+
27
+ const asksOnly = (actions: VoiceAction[]) => actions.every((a) => a.type === 'clarify' || a.type === 'none');
28
+ const intentItem = (i: { id: string; title: string; group?: string; focusName?: string; linearIdentifier?: string }): IntentItem => ({
29
+ id: i.id, title: i.title, ...(i.focusName ?? i.group ? { focusName: i.focusName ?? i.group } : {}),
30
+ ...(i.linearIdentifier ? { linearIdentifier: i.linearIdentifier } : {}),
31
+ });
32
+
33
+ function validate(req: ReplyRequest) {
34
+ if (req.subject?.kind === 'question') throw new ReplyError('Answering a question by voice is not available here yet.', 501);
35
+ if (req.subject?.kind !== 'briefing' || !req.subject.id) throw new ReplyError('Say which briefing this is a reply to.', 400);
36
+ if (!CLIENT_ACTION_ID.test(req.clientActionId ?? '')) throw new ReplyError('Send a clientActionId (8-64 letters, digits, - or _), fresh for each press.', 400);
37
+ if (!req.undo && !req.apply && req.utterance === undefined && !req.audio) throw new ReplyError('Send what was said: audio or an utterance.', 400);
38
+ if (req.audio && req.audio.audio.byteLength > MAX_REPLY_AUDIO_BYTES) throw new ReplyError('That recording is too long for a reply.', 413);
39
+ }
40
+
41
+ /** The results already recorded under this press, in order. */
42
+ function recorded(log: ActionLog, id: string): ActionResult[] {
43
+ const out: ActionResult[] = [];
44
+ for (let n = 0; log.applied[`${id}#${n}`]; n += 1) out.push(log.applied[`${id}#${n}`]);
45
+ return out;
46
+ }
47
+
48
+ async function update(deps: BriefingReplyDeps, change: (log: ActionLog) => void) {
49
+ const log = await deps.log.load();
50
+ change(log);
51
+ await deps.log.save(log);
52
+ }
53
+
54
+ async function speak(deps: BriefingReplyDeps, text: string, briefingId: string, id: string): Promise<{ confirmation: ReplyConfirmation; audio?: PendingReply['confirmAudio'] }> {
55
+ let ref = '';
56
+ const spoken: SpokenConfirmation = await speakConfirmation({
57
+ text,
58
+ clientActionId: id,
59
+ synthesize: deps.synthesize,
60
+ audio: deps.audio ? { put: deps.audio.put, url: async (r) => { ref = r; return replyAudioPath(briefingId, id); } } : undefined,
61
+ });
62
+ const confirmation: ReplyConfirmation = { text: spoken.text, audioUrl: spoken.audioUrl, ...(spoken.mimeType ? { mimeType: spoken.mimeType } : {}), ...(spoken.reason ? { reason: spoken.reason } : {}) };
63
+ return { confirmation, ...(spoken.audioUrl && ref ? { audio: { ref, mimeType: spoken.mimeType ?? 'audio/mpeg' } } : {}) };
64
+ }
65
+
66
+ export async function handleBriefingReply(deps: BriefingReplyDeps, req: ReplyRequest): Promise<ReplyResult> {
67
+ validate(req);
68
+ const now = (deps.now ?? Date.now)();
69
+ const id = req.clientActionId;
70
+ const briefingId = req.subject.id;
71
+ const store = deps.store ?? createEntityBriefingStore(deps.http, deps.ownerSub);
72
+ const record: BriefingRecord | null = await store.get(briefingId);
73
+ if (!record) throw new ReplyError('Not found.', 404);
74
+ const timeZone = req.timeZone || record.context.timeZone || deps.timeZone || 'UTC';
75
+ const log = await deps.log.load();
76
+ const mine = (log.pending ?? []).find((p) => p.id === id);
77
+
78
+ const base = {
79
+ clientActionId: id,
80
+ results: [] as ActionResult[],
81
+ question: null as string | null,
82
+ confirmation: null as ReplyConfirmation | null,
83
+ refresh: false,
84
+ replayed: false,
85
+ };
86
+
87
+ // 1. Already handled: answer from the log. Nothing is transcribed, parsed or written again.
88
+ const done = recorded(log, id);
89
+ if (done.length) {
90
+ const text = done.map((r) => r.spoken).join(' ');
91
+ const asked = mine ? asksOnly(mine.actions) : false;
92
+ return {
93
+ ...base,
94
+ kind: asked ? 'clarify' : 'applied',
95
+ utterance: mine?.utterance ?? '', understood: mine?.understood ?? '', actions: mine?.actions ?? [],
96
+ source: mine?.source ?? 'grammar', confidence: mine?.confidence ?? 1, needsConfirm: false,
97
+ results: done, question: asked ? (mine?.question ?? text) : null,
98
+ confirmation: { text, audioUrl: mine?.confirmAudio ? replyAudioPath(briefingId, id) : null, ...(mine?.confirmAudio ? { mimeType: mine.confirmAudio.mimeType } : {}) },
99
+ undoDepth: log.stack.length, refresh: false, replayed: true,
100
+ };
101
+ }
102
+
103
+ // 2. Undo: no words, straight to the executor.
104
+ let entry: PendingReply | undefined = mine;
105
+ if (req.undo) {
106
+ entry = { id, utterance: 'undo', understood: 'Undo the last change', actions: [{ type: 'undo' }], source: 'grammar', confidence: 1, at: new Date(now).toISOString() };
107
+ } else if (req.apply && !entry) {
108
+ throw new ReplyError('That reply is no longer waiting. Say it again.', 409, 'expired');
109
+ } else if (!entry) {
110
+ entry = await understand(deps, req, record, log, timeZone, now);
111
+ const kept = entry;
112
+ await update(deps, (l) => { l.pending = [...(l.pending ?? []).filter((p) => p.id !== kept.id), kept].slice(-PENDING_KEPT); });
113
+ }
114
+
115
+ // 3. Wait for a yes, or go.
116
+ const mode = req.mode ?? 'auto';
117
+ const sure = entry.confidence >= (deps.minAutoConfidence ?? DEFAULT_MIN_AUTO) && !entry.actions.some((a) => a.type === 'clarify' || a.type === 'none');
118
+ const go = req.undo || req.apply || asksOnly(entry.actions) || (mode === 'auto' && sure);
119
+ const view = { utterance: entry.utterance, understood: entry.understood, actions: entry.actions, source: entry.source, confidence: entry.confidence };
120
+ if (!go) {
121
+ return { ...base, ...view, kind: 'preview', needsConfirm: true, undoDepth: log.stack.length };
122
+ }
123
+
124
+ // 4. Apply and say it back.
125
+ const outcome = await executeVoiceActions({
126
+ actions: entry.actions, clientActionId: id, seam: deps.seam, log: deps.log, ownerSub: deps.ownerSub, now: () => now, timeZone,
127
+ });
128
+ const asked = asksOnly(entry.actions);
129
+ const question = asked ? outcome.results.map((r) => r.spoken).join(' ') : null;
130
+ const said = await speak(deps, outcome.text, briefingId, id);
131
+ const finalEntry = entry;
132
+ await update(deps, (l) => {
133
+ const rest = (l.pending ?? []).filter((p) => p.id !== finalEntry.id);
134
+ l.pending = [...rest, { ...finalEntry, ...(question ? { question } : {}), ...(said.audio ? { confirmAudio: said.audio } : {}) }].slice(-PENDING_KEPT);
135
+ });
136
+ return {
137
+ ...base, ...view,
138
+ kind: asked ? 'clarify' : 'applied', needsConfirm: false, results: outcome.results, question,
139
+ confirmation: said.confirmation, undoDepth: outcome.undoDepth, refresh: outcome.applied > 0, replayed: outcome.replayed,
140
+ };
141
+ }
142
+
143
+ /** Words -> actions, grounded in what was just read. */
144
+ async function understand(deps: BriefingReplyDeps, req: ReplyRequest, record: BriefingRecord, log: ActionLog, timeZone: string, now: number): Promise<PendingReply> {
145
+ const briefed = record.items.map(intentItem);
146
+ const briefedIds = new Set(briefed.map((i) => i.id));
147
+ // "That other thing" names an open item that was not read out: it is as likely to be misheard as a spoken one.
148
+ const open = (await deps.loadItems().catch(() => [])).filter((i) => !briefedIds.has(i.id)).map(intentItem);
149
+ let utterance = req.utterance ?? '';
150
+ if (req.audio) {
151
+ if (!deps.transcribe) throw new ReplyError('Speech to text is not set up.', 503, 'transcription_unavailable');
152
+ try {
153
+ utterance = await deps.transcribe({ audio: req.audio.audio, mimeType: req.audio.mimeType, hints: [...briefed, ...open.slice(0, MAX_HINTS)].map((i) => i.title) });
154
+ } catch (error) {
155
+ throw new ReplyError(`I could not make out the recording: ${error instanceof Error ? error.message : 'transcription failed'}`, 502, 'transcription_failed');
156
+ }
157
+ }
158
+ utterance = utterance.trim();
159
+ const at = new Date(now).toISOString();
160
+ if (!utterance) {
161
+ const actions: VoiceAction[] = [{ type: 'clarify', question: 'Sorry, I did not catch that. Can you say that again?' }];
162
+ return { id: req.clientActionId, utterance, understood: actions[0].type === 'clarify' ? actions[0].question : '', actions, source: 'grammar', confidence: 0, at };
163
+ }
164
+
165
+ const earlier = req.inReplyTo ? (log.pending ?? []).find((p) => p.id === req.inReplyTo && p.question) : undefined;
166
+ const ctx: IntentContext = {
167
+ utterance, now, timeZone, briefed, open,
168
+ readingId: req.position ? readingAt(record.context, { ...req.position, textLength: record.text.length }) : null,
169
+ hasUndo: log.stack.length > 0,
170
+ ...(earlier ? { thread: { utterance: earlier.utterance, question: earlier.question as string } } : {}),
171
+ };
172
+ const intent: IntentResult = await resolveVoiceIntent(ctx, { llm: deps.intentLlm ?? null, ...(deps.intentTimeoutMs ? { timeoutMs: deps.intentTimeoutMs } : {}) });
173
+ return { id: req.clientActionId, utterance, understood: intent.understood, actions: intent.actions, source: intent.source, confidence: intent.confidence ?? (asksOnly(intent.actions) ? 0 : 1), at };
174
+ }
@@ -0,0 +1,6 @@
1
+ export { handleBriefingReply, replyAudioPath, CLIENT_ACTION_ID } from './handle';
2
+ export { briefingReplyResponse, briefingReplyAudioResponse } from './respond';
3
+ export { ReplyError } from './types';
4
+ export type {
5
+ BriefingReplyDeps, ReplyConfirmation, ReplyRequest, ReplyResult, ReplySubject,
6
+ } from './types';
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Fetch-`Response` wrappers for the tenant frontend's route files:
3
+ * POST /corpus/briefing/reply JSON {briefingId, clientActionId, utterance?, ...} or multipart with `audio`
4
+ * GET /corpus/briefing/<id>/reply/<clientActionId>/audio the spoken confirmation, to its owner only
5
+ */
6
+ import { voiceErrorResponse } from '../../voice-manage';
7
+ import { isTimeZone } from '../../spoken-time';
8
+ import { emptyLog } from '../actions/log';
9
+ import { createEntityBriefingStore } from '../store';
10
+ import { CLIENT_ACTION_ID, MAX_REPLY_AUDIO_BYTES, handleBriefingReply } from './handle';
11
+ import { ReplyError, type BriefingReplyDeps, type ReplyRequest } from './types';
12
+
13
+ const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined);
14
+ const bool = (v: unknown) => v === true || v === 'true' || v === '1';
15
+
16
+ function position(raw: unknown): ReplyRequest['position'] {
17
+ let value = raw;
18
+ if (typeof raw === 'string') { try { value = JSON.parse(raw); } catch { return undefined; } }
19
+ if (!value || typeof value !== 'object') return undefined;
20
+ const out: NonNullable<ReplyRequest['position']> = {};
21
+ for (const key of ['charPosition', 'seconds', 'durationSeconds'] as const) {
22
+ const n = Number((value as Record<string, unknown>)[key]);
23
+ if (Number.isFinite(n) && n >= 0) out[key] = n;
24
+ }
25
+ return Object.keys(out).length ? out : undefined;
26
+ }
27
+
28
+ async function parse(request: Request): Promise<ReplyRequest> {
29
+ const type = request.headers.get('content-type') ?? '';
30
+ let fields: Record<string, unknown>;
31
+ let audio: ReplyRequest['audio'];
32
+ if (type.includes('multipart/form-data')) {
33
+ // Typed by what is used: the native build has no DOM lib, so `FormData`'s methods are not declared there.
34
+ const form = (await request.formData().catch(() => { throw new ReplyError('Send the reply as multipart form data or JSON.', 400); })) as unknown as {
35
+ entries(): Iterable<[string, unknown]>;
36
+ get(name: string): unknown;
37
+ };
38
+ fields = Object.fromEntries([...form.entries()].filter(([, v]) => typeof v === 'string'));
39
+ const file = form.get('audio');
40
+ if (file instanceof Blob && file.size > 0) {
41
+ if (file.size > MAX_REPLY_AUDIO_BYTES) throw new ReplyError('That recording is too long for a reply.', 413);
42
+ audio = { audio: new Uint8Array(await file.arrayBuffer()), mimeType: file.type || 'audio/mp4' };
43
+ }
44
+ } else {
45
+ try { fields = JSON.parse((await request.text()) || '{}'); } catch { throw new ReplyError('Send JSON, or multipart with the recording.', 400); }
46
+ if (!fields || typeof fields !== 'object') throw new ReplyError('Send JSON, or multipart with the recording.', 400);
47
+ }
48
+ const zone = str(fields.timeZone);
49
+ return {
50
+ subject: (fields.subject as ReplyRequest['subject'] | undefined) ?? { kind: 'briefing', id: str(fields.briefingId) ?? '' },
51
+ clientActionId: str(fields.clientActionId) ?? '',
52
+ ...(typeof fields.utterance === 'string' ? { utterance: fields.utterance } : {}),
53
+ ...(audio ? { audio } : {}),
54
+ ...(position(fields.position) ? { position: position(fields.position) } : {}),
55
+ ...(zone && isTimeZone(zone) ? { timeZone: zone } : {}),
56
+ ...(fields.mode === 'preview' ? { mode: 'preview' as const } : {}),
57
+ ...(bool(fields.apply) ? { apply: true } : {}),
58
+ ...(bool(fields.undo) ? { undo: true } : {}),
59
+ ...(str(fields.inReplyTo) ? { inReplyTo: str(fields.inReplyTo) } : {}),
60
+ };
61
+ }
62
+
63
+ const failure = (error: unknown) => {
64
+ if (error instanceof ReplyError) return Response.json({ detail: error.message, ...(error.code ? { code: error.code } : {}) }, { status: error.status });
65
+ return voiceErrorResponse(error);
66
+ };
67
+
68
+ export async function briefingReplyResponse(request: Request, deps: BriefingReplyDeps): Promise<Response> {
69
+ try {
70
+ return Response.json(await handleBriefingReply(deps, await parse(request)));
71
+ } catch (error) {
72
+ return failure(error);
73
+ }
74
+ }
75
+
76
+ /** The spoken confirmation of one reply. The log and the briefing are read as the caller, so anyone else's id is a 404. */
77
+ export async function briefingReplyAudioResponse(
78
+ briefingId: string,
79
+ clientActionId: string,
80
+ deps: Pick<BriefingReplyDeps, 'http' | 'ownerSub' | 'log' | 'store'> & { audio: { get(ref: string): Promise<{ audio: Uint8Array; mimeType: string }> } },
81
+ ): Promise<Response> {
82
+ const notFound = () => Response.json({ detail: 'Not found.' }, { status: 404 });
83
+ if (!CLIENT_ACTION_ID.test(clientActionId)) return notFound();
84
+ try {
85
+ const store = deps.store ?? createEntityBriefingStore(deps.http, deps.ownerSub);
86
+ if (!(await store.get(briefingId))) return notFound();
87
+ const log = await deps.log.load().catch(() => emptyLog());
88
+ const ref = (log.pending ?? []).find((p) => p.id === clientActionId)?.confirmAudio;
89
+ if (!ref) return notFound();
90
+ const { audio, mimeType } = await deps.audio.get(ref.ref);
91
+ return new Response(audio as BodyInit, { headers: { 'content-type': mimeType, 'cache-control': 'private, max-age=300', 'content-length': String(audio.byteLength) } });
92
+ } catch (error) {
93
+ return failure(error);
94
+ }
95
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * THE REPLY ENDPOINT'S SHAPES (bd startsim-t1hsu.1).
3
+ *
4
+ * One request/response pair for "the person said something back": a briefing reply
5
+ * today, and the answer to a clarifying question (epic startsim-tmrvi) tomorrow
6
+ * (`subject.kind: 'question'`). The response is one union the app can render without
7
+ * knowing which: what was understood, what changed, what to say back, and the
8
+ * question to ask when it could not tell.
9
+ */
10
+ import type { CorpusHttp } from '../../client';
11
+ import type { ActionLogStore, ActionResult, ItemEditSeam } from '../actions/types';
12
+ import type { BriefingAudio, BriefingSynthesize } from '../generate';
13
+ import type { PlaybackPosition } from '../intent/position';
14
+ import type { VoiceAction } from '../intent/types';
15
+ import type { BriefingScriptLlm } from '../script';
16
+ import type { BriefingStore } from '../store';
17
+ import type { BriefingItem } from '../types';
18
+
19
+ export type ReplySubject =
20
+ | { kind: 'briefing'; id: string }
21
+ /** Reserved for the clarifying-question loop: answers an `open_question` row. */
22
+ | { kind: 'question'; id: string };
23
+
24
+ export interface ReplyRequest {
25
+ subject: ReplySubject;
26
+ /** Fresh per press. Sending it again is a replay: nothing is transcribed, parsed or written twice. */
27
+ clientActionId: string;
28
+ /** What was said, when the app already has the words. */
29
+ utterance?: string;
30
+ /** What was said, as a recording. */
31
+ audio?: { audio: Uint8Array; mimeType: string };
32
+ /** Where the briefing was when the person pressed talk ("this one"). */
33
+ position?: PlaybackPosition;
34
+ /** The listener's IANA zone. Default: the briefing's. */
35
+ timeZone?: string;
36
+ /** `auto` applies a sure reply at once; `preview` only says what was understood. Default `auto`. */
37
+ mode?: 'auto' | 'preview';
38
+ /** Apply the preview stored under `clientActionId`. */
39
+ apply?: boolean;
40
+ /** Undo the last change (what the Undo button sends). */
41
+ undo?: boolean;
42
+ /** The client action id of the earlier reply that ended in a question; this reply answers it. */
43
+ inReplyTo?: string;
44
+ }
45
+
46
+ export interface ReplyConfirmation {
47
+ /** What is said back. */
48
+ text: string;
49
+ /** Owner-checked link to the spoken version, or null when only text is available. */
50
+ audioUrl: string | null;
51
+ mimeType?: string;
52
+ reason?: string;
53
+ }
54
+
55
+ export interface ReplyResult {
56
+ /** `preview`: understood, waiting for `apply`. `applied`: the edits ran. `clarify`: it asked instead of acting. */
57
+ kind: 'preview' | 'applied' | 'clarify';
58
+ clientActionId: string;
59
+ /** The words (transcribed if it was audio). */
60
+ utterance: string;
61
+ /** One line: "Move Order dad's bench to Friday". */
62
+ understood: string;
63
+ actions: VoiceAction[];
64
+ source: 'llm' | 'grammar';
65
+ confidence: number;
66
+ /** True while a preview waits for `apply`. */
67
+ needsConfirm: boolean;
68
+ /** What each action did (empty for a preview). */
69
+ results: ActionResult[];
70
+ /** The question, when `kind` is `clarify`. */
71
+ question: string | null;
72
+ /** The sentence to say back (confirmation, undo, or the question) and its audio; null for a preview. */
73
+ confirmation: ReplyConfirmation | null;
74
+ /** How many changes can still be undone. */
75
+ undoDepth: number;
76
+ /** True when the briefing's items changed and the list should be reloaded. */
77
+ refresh: boolean;
78
+ /** True when this press had already been handled and nothing ran again. */
79
+ replayed: boolean;
80
+ }
81
+
82
+ export interface BriefingReplyDeps {
83
+ http: Pick<CorpusHttp, 'get'> & { post<T>(path: string, body?: unknown): Promise<T> };
84
+ /** The caller, from the verified session. */
85
+ ownerSub: string;
86
+ /** The caller's open to-dos: what "that other thing" may name. */
87
+ loadItems(): Promise<BriefingItem[]>;
88
+ /** The one way an action touches an item (see `ItemEditSeam`). */
89
+ seam: ItemEditSeam;
90
+ log: ActionLogStore;
91
+ /** The intent model (temperature 0). Omit to use the plain rules alone. */
92
+ intentLlm?: BriefingScriptLlm | null;
93
+ synthesize?: BriefingSynthesize;
94
+ audio?: Pick<BriefingAudio, 'put'> & { get(audioRef: string): Promise<{ audio: Uint8Array; mimeType: string }> };
95
+ /** Speech to text for a recording; `hints` are the item titles just read. */
96
+ transcribe?: (input: { audio: Uint8Array; mimeType: string; hints: string[] }) => Promise<string>;
97
+ store?: BriefingStore;
98
+ now?: () => number;
99
+ /** Used when neither the request nor the briefing has a zone. */
100
+ timeZone?: string;
101
+ /** A model answer below this asks first even in `auto`. Default 0.85. */
102
+ minAutoConfidence?: number;
103
+ intentTimeoutMs?: number;
104
+ }
105
+
106
+ /** An error the route turns into a status; `code` lets the app choose its message. */
107
+ export class ReplyError extends Error {
108
+ constructor(message: string, readonly status: number, readonly code?: string) {
109
+ super(message);
110
+ this.name = 'ReplyError';
111
+ }
112
+ }
@@ -42,6 +42,8 @@ export type BriefingDraft = Omit<BriefingRecord, 'id'>;
42
42
 
43
43
  export interface BriefingStore {
44
44
  find(externalId: string): Promise<BriefingRecord | null>;
45
+ /** One of the caller's own briefings by row id; null for another person's row, a row of another kind or no row. */
46
+ get(id: string): Promise<BriefingRecord | null>;
45
47
  /** Shallow-merging upsert; returns the row with its id. */
46
48
  save(draft: BriefingDraft): Promise<BriefingRecord>;
47
49
  }
@@ -103,6 +105,18 @@ export function createEntityBriefingStore(http: StoreHttp, ownerSub: string): Br
103
105
  const hit = (page.results ?? []).find((r) => (r.external_id ?? r.externalId) === externalId && mine(r));
104
106
  return hit ? toRecord(hit) : null;
105
107
  },
108
+ async get(id) {
109
+ let entity: TenantEntity;
110
+ try {
111
+ entity = await http.get<TenantEntity>(`api/v1/entities/${encodeURIComponent(id)}`);
112
+ } catch (error) {
113
+ const status = (error as { status?: number }).status;
114
+ if (status === 404 || status === 403) return null;
115
+ throw error;
116
+ }
117
+ const data = (entity?.data ?? {}) as Record<string, unknown>;
118
+ return data.source === BRIEFING_SOURCE && mine(entity) ? toRecord(entity) : null;
119
+ },
106
120
  async save(draft) {
107
121
  const row = await http.post<TenantEntity>('api/v1/entities/upsert', {
108
122
  entity_type: 'source_document',
@@ -52,6 +52,8 @@ import type {
52
52
  CorpusTypeKeys, TenantEntity, TenantFacetRow, TenantRelationship,
53
53
  } from './entities';
54
54
  import { entityParams } from './entity-query';
55
+ import { encodeOwnerSubs } from './owner-link';
56
+ import { readRoster } from './roster';
55
57
  import { ABOUT_FOCUS, createFilingApi, setCommitmentFocus } from './filing';
56
58
  import {
57
59
  FOCUS_TYPE,
@@ -61,6 +63,7 @@ import {
61
63
  focusToEntity,
62
64
  toFocus,
63
65
  } from './planning';
66
+ import { commitmentOrder } from './tracker-sort';
64
67
  import type {
65
68
  Commitment,
66
69
  SaveCommitmentsOptions,
@@ -146,6 +149,8 @@ export interface CreateCorpusApiOptions {
146
149
  * picker exists to close, reappearing as an empty dropdown with no error.
147
150
  */
148
151
  members?: string;
152
+ /** The member-readable roster that supplies display names (`{sub, label}`). */
153
+ roster?: string;
149
154
  };
150
155
  /** How old a source's last sync may be before the Library calls it stale. */
151
156
  staleAfterHours?: number;
@@ -249,9 +254,9 @@ function commitmentParams(query: CommitmentQuery, type: string): Record<string,
249
254
  type,
250
255
  page: query.page ?? 1,
251
256
  ...(query.pageSize ? { page_size: Math.min(query.pageSize, 200) } : {}),
252
- // Oldest debt first, which is what the screen sorts by anyway — asking the
253
- // server for it means page one is the right page one.
254
- order: 'attr.due_at',
257
+ // Oldest debt first unless the screen asks otherwise — asking the server
258
+ // means page one is the right page one.
259
+ order: commitmentOrder(query.sort),
255
260
  };
256
261
  if (statuses.length === 1) out['attr.status'] = statuses[0];
257
262
  else if (statuses.length > 1) out['attr.status__in'] = statuses.join(',');
@@ -1201,6 +1206,7 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1201
1206
  const relationships = options.paths?.relationships ?? 'api/v1/relationships';
1202
1207
  // tenant-starter/config/urls.py: path("api/v1/org/members/", OrgMembersView…)
1203
1208
  const membersPath = options.paths?.members ?? 'api/v1/org/members';
1209
+ const rosterPath = options.paths?.roster ?? 'api/v1/org/roster';
1204
1210
 
1205
1211
  function writer(): NonNullable<CorpusHttp['post']> {
1206
1212
  if (!http.post) {
@@ -1406,6 +1412,12 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1406
1412
  if (patch.statusReason !== undefined) wire.status_reason = patch.statusReason;
1407
1413
  if (patch.ownerName !== undefined) wire.owner_name = patch.ownerName;
1408
1414
  if (patch.ownerSub !== undefined) wire.owner_sub = patch.ownerSub;
1415
+ // Joint owners: the list and its first member move together, so a reader of
1416
+ // only `owner_sub` never sees a different person than `owner_subs` does.
1417
+ if (patch.ownerSubs !== undefined) {
1418
+ wire.owner_subs = encodeOwnerSubs(patch.ownerSubs);
1419
+ wire.owner_sub = patch.ownerSubs[0] ?? '';
1420
+ }
1409
1421
  if (patch.dueAt !== undefined) wire.due_at = patch.dueAt;
1410
1422
  if (patch.subtype !== undefined) wire.subtype = patch.subtype;
1411
1423
  if (patch.priority !== undefined) wire.priority = patch.priority;
@@ -1456,21 +1468,7 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1456
1468
  * alongside `ownerSub` instead of being replaced by it.
1457
1469
  */
1458
1470
  async listMembers(): Promise<Array<{ sub: string; email: string; name?: string }>> {
1459
- try {
1460
- const page = await http.get<DrfPage<Record<string, unknown>>>(membersPath, {});
1461
- return (page.results ?? [])
1462
- .map((row) => {
1463
- const user = (row.user ?? {}) as Record<string, unknown>;
1464
- return {
1465
- sub: String(user.sub ?? row.sub ?? ''),
1466
- email: String(user.email ?? row.email ?? ''),
1467
- ...(user.name ? { name: String(user.name) } : {}),
1468
- };
1469
- })
1470
- .filter((member) => member.sub);
1471
- } catch {
1472
- return [];
1473
- }
1471
+ return readRoster(http, { members: membersPath, roster: rosterPath });
1474
1472
  },
1475
1473
  };
1476
1474
  }
@@ -23,6 +23,7 @@
23
23
  * row with a missing subtitle.
24
24
  */
25
25
  import { withSourceEntity } from './source-entity';
26
+ import { decodeOwnerSubs, encodeOwnerSubs } from './owner-link';
26
27
  import { readItemSync, type ItemSync } from '../task-tracker/item-sync';
27
28
  import { filingsFromRow } from './voice-sections';
28
29
  import type {
@@ -736,6 +737,8 @@ export function toCommitment(
736
737
  ? { dueConfidence: asNumber(pick(data, 'due_confidence', 'dueConfidence')) } : {}),
737
738
  ...(pick(data, 'owner_sub', 'ownerSub')
738
739
  ? { ownerSub: asText(pick(data, 'owner_sub', 'ownerSub')) } : {}),
740
+ ...(decodeOwnerSubs(pick(data, 'owner_subs', 'ownerSubs')).length
741
+ ? { ownerSubs: decodeOwnerSubs(pick(data, 'owner_subs', 'ownerSubs')) } : {}),
739
742
  // Both spellings, for the reason spelled out on ORIGIN_KEY above: the
740
743
  // browser client camelCases `_origin` into `Origin` on the way in, and a
741
744
  // server-side fetch does not.
@@ -812,6 +815,7 @@ export function commitmentToEntity(commitment: Commitment): {
812
815
  ...(commitment.dueBasis ? { due_basis: commitment.dueBasis } : {}),
813
816
  ...(commitment.dueConfidence !== undefined ? { due_confidence: commitment.dueConfidence } : {}),
814
817
  ...(commitment.ownerSub ? { owner_sub: commitment.ownerSub } : {}),
818
+ ...(commitment.ownerSubs?.length ? { owner_subs: encodeOwnerSubs(commitment.ownerSubs) } : {}),
815
819
  ...(commitment.destination ? { destination: commitment.destination } : {}),
816
820
  ...(commitment.externalFocusId ? { external_focus_id: commitment.externalFocusId } : {}),
817
821
  ...(commitment.externalContainerId ? { external_container_id: commitment.externalContainerId } : {}),