@startsimpli/integrations 0.2.223 → 0.2.225

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/package.json +5 -5
  2. package/src/__tests__/attention-importance.test.ts +51 -0
  3. package/src/__tests__/attention-policy.test.ts +174 -0
  4. package/src/__tests__/attention-rhythm.test.ts +95 -0
  5. package/src/__tests__/attention-run.test.ts +132 -0
  6. package/src/__tests__/attention-settings-page.test.tsx +57 -0
  7. package/src/__tests__/attention-settings.test.ts +86 -0
  8. package/src/__tests__/converse-client.test.ts +6 -0
  9. package/src/__tests__/converse-meeting.test.ts +40 -0
  10. package/src/__tests__/converse-relay.test.ts +35 -0
  11. package/src/__tests__/converse-roci.test.ts +16 -1
  12. package/src/__tests__/converse-soak.test.ts +61 -0
  13. package/src/__tests__/converse-watchdog.test.ts +107 -0
  14. package/src/__tests__/decisions-page.test.tsx +1 -1
  15. package/src/__tests__/fleet-view.test.ts +1 -1
  16. package/src/__tests__/relay-items.test.ts +89 -0
  17. package/src/components/index.ts +1 -0
  18. package/src/components/pages/AttentionSettings.tsx +51 -0
  19. package/src/components/pages/DecisionsPage.tsx +13 -2
  20. package/src/corpus/attention/controller.ts +37 -0
  21. package/src/corpus/attention/importance.ts +17 -0
  22. package/src/corpus/attention/index.ts +9 -0
  23. package/src/corpus/attention/policy.ts +61 -0
  24. package/src/corpus/attention/push.ts +47 -0
  25. package/src/corpus/attention/queue.ts +26 -0
  26. package/src/corpus/attention/rhythm.ts +69 -0
  27. package/src/corpus/attention/run-steps.ts +90 -0
  28. package/src/corpus/attention/run.ts +65 -0
  29. package/src/corpus/attention/settings.ts +80 -0
  30. package/src/corpus/attention/types.ts +75 -0
  31. package/src/corpus/converse/client.ts +3 -2
  32. package/src/corpus/converse/handle.ts +18 -3
  33. package/src/corpus/converse/meeting-config.ts +15 -1
  34. package/src/corpus/converse/meeting.ts +100 -8
  35. package/src/corpus/converse/respond.ts +12 -2
  36. package/src/corpus/converse/roci.ts +11 -4
  37. package/src/corpus/converse/types.ts +11 -0
  38. package/src/corpus/index.ts +1 -0
  39. package/src/corpus/notify/client.ts +10 -2
  40. package/src/corpus/notify/handle.ts +9 -5
  41. package/src/corpus/notify/index.ts +2 -0
  42. package/src/corpus/notify/relay-items.ts +53 -0
  43. package/src/corpus/notify/respond.ts +7 -1
  44. package/src/corpus/notify/state.ts +4 -0
  45. package/src/corpus/notify/types.ts +14 -0
  46. package/src/native/app/converseServices.ts +1 -0
  47. package/src/native/app/notifyServices.ts +8 -1
  48. package/src/native/app/registry.tsx +4 -2
  49. package/src/native/app/services.ts +1 -1
  50. package/src/native/converse/DriveScreen.tsx +47 -0
  51. package/src/native/converse/__tests__/driveScreen.test.tsx +54 -0
  52. package/src/native/converse/api.ts +1 -0
  53. package/src/native/converse/fake.ts +4 -0
  54. package/src/native/converse/index.ts +1 -0
  55. package/src/native/converse/io.ts +1 -0
  56. package/src/native/push/AttentionCard.tsx +44 -0
  57. package/src/native/push/DecisionsScreen.tsx +12 -2
  58. package/src/native/push/NeedsYouCard.tsx +42 -0
  59. package/src/native/push/__tests__/decisionsApp.test.tsx +12 -1
  60. package/src/native/push/__tests__/needsYou.test.tsx +106 -0
  61. package/src/native/push/fake.ts +12 -1
  62. package/src/native/push/index.ts +3 -0
  63. package/src/native/push/needsYou.ts +29 -0
  64. package/src/native/push/tab.tsx +4 -2
  65. package/src/native/talk/TalkTab.tsx +24 -2
@@ -0,0 +1,61 @@
1
+ /** The pure part: classify an item, read the quiet window, merge policy overrides. No I/O, no clock of its own. */
2
+ import { ATTENTION_DEFAULTS, type AttentionClass, type AttentionItem, type AttentionPolicy, type AttentionPolicyInput } from './types';
3
+
4
+ export function resolveAttentionPolicy(over: AttentionPolicyInput = {}): AttentionPolicy {
5
+ const d = ATTENTION_DEFAULTS;
6
+ return {
7
+ ...d, ...over,
8
+ quiet: { ...d.quiet, ...over.quiet }, importanceWeights: { ...d.importanceWeights, ...over.importanceWeights }, brief: { ...d.brief, ...over.brief }, wrap: { ...d.wrap, ...over.wrap },
9
+ };
10
+ }
11
+
12
+ const compile = (sources: string[]): RegExp[] => sources.flatMap((s) => { try { return [new RegExp(s, 'i')]; } catch { return []; } });
13
+
14
+ export function classifyItem(item: AttentionItem, policy: AttentionPolicy): AttentionClass {
15
+ // The relay asks a question and waits for his answer: it never interrupts (needs-answer), whatever words the question has.
16
+ if (item.source === 'relay') return 'needs-answer';
17
+ const words = policy.urgentWords.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).filter(Boolean).map((w) => `(^|[^\\w])${w}($|[^\\w])`);
18
+ if (compile([...policy.urgentPatterns, ...words]).some((r) => r.test(item.text))) return 'urgent';
19
+ if (compile(policy.noisePatterns).some((r) => r.test(item.text))) return 'noise';
20
+ if (compile(policy.digestPatterns).some((r) => r.test(item.text))) return 'digest';
21
+ if (item.source === 'decision') return 'needs-answer';
22
+ return policy.notifyScope === 'decisions+fleet' ? 'needs-answer' : 'digest';
23
+ }
24
+
25
+ /** Local hour (0-23) in `timeZone`; falls back to UTC for a zone the runtime does not know. */
26
+ export function hourIn(now: number, timeZone: string): number {
27
+ const parts = (tz?: string) => new Intl.DateTimeFormat('en-US', { hour: 'numeric', hourCycle: 'h23', ...(tz ? { timeZone: tz } : { timeZone: 'UTC' }) }).formatToParts(new Date(now));
28
+ let p;
29
+ try { p = parts(timeZone); } catch { p = parts(); }
30
+ return Number(p.find((x) => x.type === 'hour')?.value ?? 0) % 24;
31
+ }
32
+
33
+ export function inQuietHours(now: number, quiet: AttentionPolicy['quiet']): boolean {
34
+ if (!quiet.enabled || quiet.start === quiet.end) return false;
35
+ const h = hourIn(now, quiet.timeZone);
36
+ return quiet.start < quiet.end ? h >= quiet.start && h < quiet.end : h >= quiet.start || h < quiet.end;
37
+ }
38
+
39
+ export type QuietMode = 'auto' | 'on' | 'off';
40
+
41
+ /** The manual toggle over the schedule: `off` (the default) never quiet, `on` quiet all day, `auto` follows the hours. */
42
+ export const isQuiet = (now: number, quiet: AttentionPolicy['quiet'], mode: QuietMode = 'off'): boolean => (mode === 'on' ? true : mode === 'off' ? false : inQuietHours(now, quiet));
43
+
44
+ /** A stable id for a line of text: case, spacing and trailing punctuation do not change it. Matches the notify id format. */
45
+ export function itemId(text: string): string {
46
+ const norm = text.toLowerCase().replace(/\s+/g, ' ').replace(/[\s.!?]+$/, '').trim();
47
+ let a = 0x811c9dc5; let b = 0x1b873593;
48
+ for (let i = 0; i < norm.length; i += 1) {
49
+ const c = norm.charCodeAt(i);
50
+ a = Math.imul(a ^ c, 0x01000193) >>> 0;
51
+ b = Math.imul(b ^ c, 0x85ebca6b) >>> 0;
52
+ b = (b ^ (b >>> 13)) >>> 0;
53
+ }
54
+ return `q-${a.toString(16).padStart(8, '0')}${b.toString(16).padStart(8, '0')}`;
55
+ }
56
+
57
+ /** The calendar date (YYYY-MM-DD) in `timeZone`, UTC for a zone the runtime does not know. */
58
+ export function localDate(now: number, timeZone: string): string {
59
+ const fmt = (tz: string) => new Intl.DateTimeFormat('en-CA', { timeZone: tz, year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(now));
60
+ try { return fmt(timeZone); } catch { return fmt('UTC'); }
61
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Pushes for the queue, on every fleet snapshot: one ping per urgent item (always, even in quiet hours) and one call-me
3
+ * ping when enough are waiting (held in quiet hours). Idempotent: each ping id is derived from its content, and `notify`
4
+ * skips an id it has already recorded, so a snapshot re-posted every two minutes pushes once.
5
+ * Decisions are not re-pushed here: `createDecision` already pushes them.
6
+ */
7
+ import type { FleetView } from '../converse/fleet-view';
8
+ import { loadState } from '../notify/state';
9
+ import { notify } from '../notify/handle';
10
+ import type { NotifyDeps } from '../notify/types';
11
+ import { isQuiet, itemId, resolveAttentionPolicy } from './policy';
12
+ import { policyFrom } from './settings';
13
+ import { buildNeedsYou } from './queue';
14
+ import { answerRoutine, sendBatches } from './rhythm';
15
+ import type { AttentionPolicyInput, NeedsYouQueue, QueuedItem } from './types';
16
+
17
+ export interface AttentionPush { reason: 'urgent' | 'call-me' | 'brief' | 'wrap'; ping_id: string; delivered: number; skipped: string | null }
18
+
19
+ export const callMeTitle = (n: number) => `${n} things need you`;
20
+
21
+ export async function runAttention(deps: NotifyDeps, input: { view: Pick<FleetView, 'waitingOnQuinn'> | null; policy?: AttentionPolicyInput; now?: number }): Promise<{ queue: NeedsYouQueue; pushed: AttentionPush[]; autoAnswered: string[] }> {
22
+ const first = await loadState(deps);
23
+ const policy = resolveAttentionPolicy({ ...policyFrom(first.attention), ...input.policy });
24
+ const autoAnswered = await answerRoutine(deps, policy);
25
+ const state = autoAnswered.length ? await loadState(deps) : first;
26
+ const now = input.now ?? (deps.now ?? Date.now)();
27
+ const queue = buildNeedsYou({ view: input.view, decisions: state.decisions, policy, answered: state.answered, relay: state.relay_items });
28
+ const pushed: AttentionPush[] = [];
29
+
30
+ for (const it of queue.items.filter((i): i is QueuedItem => i.class === 'urgent')) {
31
+ const known = state.pings.some((p) => p.id === it.id);
32
+ const out = await notify(deps, { kind: 'attention', title: `Urgent: ${it.text}`, body: 'Tap to talk it through.', priority: 'high', ping_id: it.id }, state);
33
+ if (!known) pushed.push({ reason: 'urgent', ping_id: out.ping_id, delivered: out.delivered, skipped: out.skipped });
34
+ }
35
+
36
+ if (queue.callMe && !isQuiet(now, policy.quiet, state.attention?.quiet_mode)) {
37
+ const waiting = queue.items.filter((i) => i.class === 'urgent' || i.class === 'needs-answer');
38
+ const id = `callme-${itemId(waiting.map((w) => w.id).sort().join(','))}`.slice(0, 40);
39
+ const fresh = (await loadState(deps)).pings.every((p) => p.id !== id);
40
+ if (fresh) {
41
+ const out = await notify(deps, { kind: 'attention', title: callMeTitle(waiting.length), body: waiting.slice(0, 3).map((w) => w.text).join(' · '), priority: 'high', ping_id: id });
42
+ pushed.push({ reason: 'call-me', ping_id: out.ping_id, delivered: out.delivered, skipped: out.skipped });
43
+ }
44
+ }
45
+ pushed.push(...await sendBatches(deps, { policy, queue, now, quietMode: state.attention?.quiet_mode }));
46
+ return { queue, pushed, autoAnswered };
47
+ }
@@ -0,0 +1,26 @@
1
+ /** The "needs you" queue: the fleet's waiting-on-Quinn lines plus his pending decisions, classified. */
2
+ import type { FleetView } from '../converse/fleet-view';
3
+ import type { DecisionIndexRow, RelayItem } from '../notify/types';
4
+ import { importanceOf } from './importance';
5
+ import { classifyItem, itemId } from './policy';
6
+ import type { AttentionClass, AttentionItem, AttentionPolicy, NeedsYouQueue, QueuedItem } from './types';
7
+
8
+ const ORDER: AttentionClass[] = ['urgent', 'needs-answer', 'digest', 'noise'];
9
+ const clean = (s: string) => s.replace(/`|\*\*/g, '').replace(/\s+/g, ' ').trim();
10
+
11
+ export function buildNeedsYou(input: { view: Pick<FleetView, 'waitingOnQuinn'> | null; decisions: DecisionIndexRow[]; policy: AttentionPolicy; /** Items already answered (by id): they leave the queue. */ answered?: Record<string, unknown>; /** Questions the relay posted for him (their own list, never touched by the fleet snapshot). */ relay?: RelayItem[] }): NeedsYouQueue {
12
+ type Raw = Omit<AttentionItem, 'id'> & { id?: string };
13
+ const rawIn: Raw[] = [
14
+ ...(input.relay ?? []).map((r) => ({ id: `relay:${r.id}`, text: clean(r.text), source: 'relay' as const, ...(r.options?.length ? { options: r.options } : {}), ...(r.source ? { from: r.source } : {}), ...(r.link ? { link: r.link } : {}) })),
15
+ ...input.decisions.filter((d) => d.status === 'pending').map((d) => ({ text: clean(d.title), source: 'decision' as const, ref: d.id })),
16
+ ...(input.view?.waitingOnQuinn ?? []).map((t) => ({ text: clean(t), source: 'fleet' as const })),
17
+ ];
18
+ const raw: AttentionItem[] = rawIn.filter((i) => i.text).map((i) => ({ ...i, id: i.id ?? itemId(i.text) }));
19
+ const seen = new Set<string>(Object.keys(input.answered ?? {}));
20
+ const all: QueuedItem[] = raw.filter((i) => !seen.has(i.id) && seen.add(i.id)).map((i) => { const cls = classifyItem(i, input.policy); return { ...i, class: cls, importance: importanceOf(i, cls, input.policy) }; });
21
+ const counts: Record<AttentionClass, number> = { urgent: 0, 'needs-answer': 0, digest: 0, noise: 0 };
22
+ for (const i of all) counts[i.class] += 1;
23
+ const items = all.filter((i) => i.class !== 'noise').sort((a, b) => b.importance - a.importance || ORDER.indexOf(a.class) - ORDER.indexOf(b.class));
24
+ const waiting = all.filter((i) => (i.class === 'urgent' || i.class === 'needs-answer') && i.importance >= input.policy.callMeMinImportance).length;
25
+ return { items, counts, callMe: waiting >= input.policy.callMeAt, waiting };
26
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The daily rhythm and the routine answers (bd startsim-nd3qa.3). Both run on the same fleet-snapshot heartbeat as the
3
+ * urgent pushes, so there is no second scheduler: a batch is "due" once the local hour is reached, and its id carries the
4
+ * date, so the repeated snapshots send it once a day.
5
+ */
6
+ import { answerDecision, getDecision, notify } from '../notify/handle';
7
+ import { loadState, saveState } from '../notify/state';
8
+ import type { NotifyDeps } from '../notify/types';
9
+ import { classifyItem, hourIn, isQuiet, itemId, localDate } from './policy';
10
+ import type { AttentionPush } from './push';
11
+ import type { AttentionPolicy, NeedsYouQueue } from './types';
12
+
13
+ /** How long after its hour a batch is still worth sending (a relay that was down at 8 still delivers the morning one at 10). */
14
+ const BATCH_WINDOW_HOURS = 4;
15
+ export const ROUTINE_ANSWER = 'Yes, continue.';
16
+
17
+ const compile = (sources: string[]): RegExp[] => sources.flatMap((s) => { try { return [new RegExp(s, 'i')]; } catch { return []; } });
18
+
19
+ /** Answers pending single-question decisions that only ask to continue. Urgent ones and real questions are left for him. */
20
+ export async function answerRoutine(deps: NotifyDeps, policy: AttentionPolicy): Promise<string[]> {
21
+ if (!policy.selfAnswerRoutine) return [];
22
+ const state = await loadState(deps);
23
+ const routine = compile(policy.routinePatterns);
24
+ const done: string[] = [];
25
+ for (const row of state.decisions.filter((d) => d.status === 'pending')) {
26
+ const item = { id: itemId(row.title), text: row.title, source: 'decision' as const, ref: row.id };
27
+ if (classifyItem(item, policy) === 'urgent' || !routine.some((r) => r.test(row.title))) continue;
28
+ try {
29
+ const d = await getDecision(deps, row.id);
30
+ if (d.questions.length !== 1) continue;
31
+ await answerDecision(deps, row.id, { answer: ROUTINE_ANSWER });
32
+ const fresh = await loadState(deps);
33
+ await saveState(deps, { ...fresh, answered: { ...fresh.answered, [item.id]: { answer: ROUTINE_ANSWER, at: new Date((deps.now ?? Date.now)()).toISOString(), conversation_id: 'auto', ref: row.id, delivered: 'decision' } } });
34
+ done.push(row.id);
35
+ } catch (e) { console.error('[attention] could not answer a routine decision', e); }
36
+ }
37
+ return done;
38
+ }
39
+
40
+ /** The morning and end-of-day batches: one push each per local day, once its hour has come, held while quiet. */
41
+ export async function sendBatches(deps: NotifyDeps, input: { policy: AttentionPolicy; queue: NeedsYouQueue; now: number; quietMode?: 'auto' | 'on' | 'off' }): Promise<AttentionPush[]> {
42
+ const { policy, queue, now } = input;
43
+ if (isQuiet(now, policy.quiet, input.quietMode)) return [];
44
+ const tz = policy.quiet.timeZone;
45
+ const hour = hourIn(now, tz);
46
+ const date = localDate(now, tz);
47
+ const state = await loadState(deps);
48
+ const waiting = queue.items;
49
+ const pushed: AttentionPush[] = [];
50
+ const due = (h: number) => hour >= h && hour < h + BATCH_WINDOW_HOURS;
51
+
52
+ if (due(policy.brief.hour) && waiting.length) {
53
+ const id = `brief-${date}`;
54
+ if (!state.pings.some((p) => p.id === id)) {
55
+ const out = await notify(deps, { kind: 'attention', title: `Morning: ${waiting.length} waiting for you`, body: waiting.slice(0, 3).map((w) => w.text).join(' · '), priority: 'normal', ping_id: id }, state);
56
+ pushed.push({ reason: 'brief', ping_id: out.ping_id, delivered: out.delivered, skipped: out.skipped });
57
+ }
58
+ }
59
+ if (due(policy.wrap.hour)) {
60
+ const id = `wrap-${date}`;
61
+ const answeredToday = Object.values(state.answered ?? {}).filter((a) => localDate(Date.parse(a.at), tz) === date).length;
62
+ const fresh = await loadState(deps);
63
+ if ((waiting.length || answeredToday) && !fresh.pings.some((p) => p.id === id)) {
64
+ const out = await notify(deps, { kind: 'attention', title: `End of day: ${waiting.length} still open, ${answeredToday} answered today`, body: waiting.slice(0, 3).map((w) => w.text).join(' · ') || 'Nothing left waiting.', priority: 'normal', ping_id: id }, fresh);
65
+ pushed.push({ reason: 'wrap', ping_id: out.ping_id, delivered: out.delivered, skipped: out.skipped });
66
+ }
67
+ }
68
+ return pushed;
69
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The needs-you BRIEFING as a small state machine (bd startsim-nd3qa): the assistant itself asks item i of n, waits for the
3
+ * answer, records it, moves on, and ends by saying what it did. Pure: the caller stores the run and speaks the text.
4
+ * Never a chat message: nothing here is ever shown as something the person said.
5
+ */
6
+ export interface RunItem { id: string; text: string; ref?: string; /** A choice instead of yes/no. */ options?: string[] }
7
+ export interface RunAnswer { answer: string; at: string }
8
+ export interface AttentionRunState {
9
+ conversation_id: string;
10
+ items: RunItem[];
11
+ index: number;
12
+ answers: Record<string, RunAnswer>;
13
+ /** Items he put off: they stay in the queue and are not asked again in this run. */
14
+ skipped: string[];
15
+ status: 'asking' | 'done';
16
+ started_at: string;
17
+ }
18
+ export interface RunReply { text: string; active: boolean; index: number; of: number; recorded?: { item: RunItem; answer: string } }
19
+
20
+ const YES = /^\s*(yes|yeah|yep|yup|sure|ok|okay|approve[d]?|go ahead|do it|affirmative|correct|please do)\b/i;
21
+ const NO = /^\s*(no|nope|nah|don'?t|do not|hold off|negative|reject)\b/i;
22
+ const SKIP = /\b(skip|later|not now|next one|pass|come back)\b/i;
23
+ const AGAIN = /\b(again|repeat|what was that|say that|come again|didn'?t (catch|hear))\b/i;
24
+ const STOP = /^\s*(stop|cancel|that(?:'?s| is) (all|it|enough)|done|enough|never ?mind)\b/i;
25
+
26
+ export type Heard = { kind: 'yes' | 'no' } | { kind: 'skip' } | { kind: 'again' } | { kind: 'stop' } | { kind: 'free'; text: string };
27
+
28
+ export function hear(utterance: string): Heard {
29
+ const u = utterance.trim();
30
+ if (STOP.test(u)) return { kind: 'stop' };
31
+ if (AGAIN.test(u)) return { kind: 'again' };
32
+ if (SKIP.test(u)) return { kind: 'skip' };
33
+ if (YES.test(u)) return { kind: 'yes' };
34
+ if (NO.test(u)) return { kind: 'no' };
35
+ return { kind: 'free', text: u };
36
+ }
37
+
38
+ const plain = (s: string) => s.replace(/\s+/g, ' ').replace(/[.?!]+$/, '').trim();
39
+ export const questionText = (run: Pick<AttentionRunState, 'items' | 'index'>): string => {
40
+ const item = run.items[run.index];
41
+ const ask = item.options?.length ? `Say ${item.options.length === 2 ? item.options.join(' or ') : `${item.options.slice(0, -1).join(', ')} or ${item.options[item.options.length - 1]}`}.` : 'Yes or no?';
42
+ return `Question ${run.index + 1} of ${run.items.length}: ${plain(item.text)}. ${ask}`;
43
+ };
44
+ const reply = (run: AttentionRunState, text: string, recorded?: RunReply['recorded']): RunReply => ({ text, active: run.status === 'asking', index: Math.min(run.index, run.items.length), of: run.items.length, ...(recorded ? { recorded } : {}) });
45
+
46
+ export function startRun(input: { conversationId: string; items: RunItem[]; now: string }): { run: AttentionRunState; reply: RunReply } {
47
+ const run: AttentionRunState = { conversation_id: input.conversationId, items: input.items, index: 0, answers: {}, skipped: [], status: input.items.length ? 'asking' : 'done', started_at: input.now };
48
+ if (!input.items.length) return { run, reply: reply(run, 'Nothing is waiting on you right now.') };
49
+ const n = input.items.length;
50
+ return { run, reply: reply(run, `${n === 1 ? 'One thing needs you.' : `${n} things need you, most important first.`} ${questionText(run)}`) };
51
+ }
52
+
53
+ function finish(run: AttentionRunState, lead: string): { run: AttentionRunState; reply: RunReply } {
54
+ const next: AttentionRunState = { ...run, status: 'done' };
55
+ const saved = Object.keys(next.answers).length;
56
+ const left = next.items.length - saved;
57
+ const tail = saved === 0 ? 'I did not record any answers.' : `I saved ${saved} answer${saved === 1 ? '' : 's'} in your queue.`;
58
+ const rest = left > 0 ? ` ${left} ${left === 1 ? 'item is' : 'items are'} still waiting in your queue.` : '';
59
+ return { run: next, reply: reply(next, `${lead} ${tail}${rest}`) };
60
+ }
61
+
62
+ /** One step on what he said. Returns the new run and what to say. */
63
+ export function stepRun(run: AttentionRunState, utterance: string, now: string): { run: AttentionRunState; reply: RunReply } {
64
+ if (run.status !== 'asking') return { run, reply: reply(run, 'That list is finished.') };
65
+ const heard = hear(utterance);
66
+ const item = run.items[run.index];
67
+ const advance = (r: AttentionRunState, lead: string, recorded?: RunReply['recorded']) => {
68
+ const nextIndex = r.index + 1;
69
+ if (nextIndex >= r.items.length) {
70
+ const done = finish({ ...r, index: nextIndex }, `${lead} That was the last one.`.trim());
71
+ return { run: done.run, reply: { ...done.reply, ...(recorded ? { recorded } : {}) } };
72
+ }
73
+ const moved = { ...r, index: nextIndex };
74
+ return { run: moved, reply: reply(moved, `${lead} ${questionText(moved)}`.trim(), recorded) };
75
+ };
76
+ switch (heard.kind) {
77
+ case 'again': return { run, reply: reply(run, questionText(run)) };
78
+ case 'stop': return finish(run, 'Okay, stopping here.');
79
+ case 'skip': return advance({ ...run, skipped: [...run.skipped, item.id] }, 'Okay, later.');
80
+ case 'free': {
81
+ if (!heard.text) return { run, reply: reply(run, `I did not catch that. ${questionText(run)}`) };
82
+ const answered = { ...run, answers: { ...run.answers, [item.id]: { answer: heard.text.slice(0, 500), at: now } } };
83
+ return advance(answered, 'Got it.', { item, answer: heard.text.slice(0, 500) });
84
+ }
85
+ default: {
86
+ const answered = { ...run, answers: { ...run.answers, [item.id]: { answer: heard.kind, at: now } } };
87
+ return advance(answered, heard.kind === 'yes' ? 'Yes, noted.' : 'No, noted.', { item, answer: heard.kind });
88
+ }
89
+ }
90
+ }
@@ -0,0 +1,65 @@
1
+ /** The stored needs-you briefing: start it from the real queue, take answers, record them in the queue, deliver decision answers. */
2
+ import { loadFleetSnapshot } from '../converse/fleet';
3
+ import { buildFleetView } from '../converse/fleet-view';
4
+ import { answerDecision, getDecision } from '../notify/handle';
5
+ import { loadState, saveState } from '../notify/state';
6
+ import type { NotifyDeps } from '../notify/types';
7
+ import { buildNeedsYou } from './queue';
8
+ import { startRun, stepRun, type RunReply } from './run-steps';
9
+ import { policyFrom } from './settings';
10
+
11
+ export interface AttentionRunApi {
12
+ /** Begins a briefing in this conversation; the reply is what the assistant says first. */
13
+ start(conversationId: string): Promise<RunReply>;
14
+ /** Takes what he said as the answer to the current question; null when no briefing is running in this conversation. */
15
+ answer(conversationId: string, utterance: string): Promise<RunReply | null>;
16
+ }
17
+
18
+ /** What the relay is told when he answers one of its questions. */
19
+ export interface RelayDelivery { id: string; text: string; answer: string; source?: string; link?: string }
20
+
21
+ export function createAttentionRun(deps: Pick<NotifyDeps, 'http' | 'ownerSub' | 'now'>, opts: { batch?: number; /** Tells the relay his answer (the server runs the bridge). A failure keeps the answer stored for the relay to read back. */ deliverRelay?: (d: RelayDelivery) => Promise<void> } = {}): AttentionRunApi {
22
+ const nowIso = () => new Date((deps.now ?? Date.now)()).toISOString();
23
+ return {
24
+ async start(conversationId) {
25
+ const state = await loadState(deps);
26
+ const snap = await loadFleetSnapshot(deps as never).catch(() => null);
27
+ const policy = policyFrom(state.attention);
28
+ const queue = buildNeedsYou({ view: snap?.inputs ? buildFleetView(snap.inputs) : null, decisions: state.decisions, policy, answered: state.answered, relay: state.relay_items });
29
+ // Fleet lines are prose, not questions: they stay in the queue (and still drive pushes) but are never asked as yes/no. The relay posts real questions through relay-items, with options.
30
+ const items = queue.items.filter((i) => i.source !== 'fleet' && (i.class === 'urgent' || i.class === 'needs-answer')).slice(0, opts.batch ?? policy.briefBatch).map((i) => ({ id: i.id, text: i.text, ...(i.ref ? { ref: i.ref } : {}), ...(i.options?.length ? { options: i.options } : {}) }));
31
+ const { run, reply } = startRun({ conversationId, items, now: nowIso() });
32
+ await saveState(deps as never, { ...state, attention_run: run });
33
+ return reply;
34
+ },
35
+ async answer(conversationId, utterance) {
36
+ const state = await loadState(deps);
37
+ const current = state.attention_run;
38
+ if (!current || current.status !== 'asking' || current.conversation_id !== conversationId) return null;
39
+ const { run, reply } = stepRun(current, utterance, nowIso());
40
+ let answered = state.answered;
41
+ if (reply.recorded) {
42
+ const { item, answer } = reply.recorded;
43
+ let delivered: 'decision' | 'relay' | undefined;
44
+ let deliveryFailed = false;
45
+ const relayItem = item.id.startsWith('relay:') ? (state.relay_items ?? []).find((r) => `relay:${r.id}` === item.id) : undefined;
46
+ if (relayItem && opts.deliverRelay) {
47
+ try { await opts.deliverRelay({ id: relayItem.id, text: relayItem.text, answer, ...(relayItem.source ? { source: relayItem.source } : {}), ...(relayItem.link ? { link: relayItem.link } : {}) }); delivered = 'relay'; }
48
+ catch (e) { deliveryFailed = true; console.error('[attention] could not tell the relay his answer (kept for it to read back)', e); }
49
+ }
50
+ if (item.ref) {
51
+ // A decision with ONE question takes his answer directly; a longer one is only recorded here.
52
+ try {
53
+ const d = await getDecision(deps as never, item.ref);
54
+ if (d.questions.length === 1) { await answerDecision(deps as never, item.ref, { answer }); delivered = 'decision'; }
55
+ } catch (e) { console.error('[attention] could not deliver the answer to its decision', e); }
56
+ }
57
+ answered = { ...state.answered, [item.id]: { answer, at: nowIso(), conversation_id: conversationId, ...(item.ref ? { ref: item.ref } : {}), ...(delivered ? { delivered } : {}), ...(relayItem ? { source: 'relay' as const } : {}), ...(deliveryFailed ? { delivery_failed: true } : {}) } };
58
+ const keys = Object.keys(answered);
59
+ if (keys.length > 300) answered = Object.fromEntries(keys.slice(-300).map((k) => [k, answered![k]]));
60
+ }
61
+ await saveState(deps as never, { ...state, attention_run: run, ...(answered ? { answered } : {}) });
62
+ return reply;
63
+ },
64
+ };
65
+ }
@@ -0,0 +1,80 @@
1
+ /** What the person can tune, stored on their notify state: quiet mode and schedule, urgent words, call-me threshold, scope. */
2
+ import { NotifyError } from '../notify/types';
3
+ import { isQuiet, resolveAttentionPolicy, type QuietMode } from './policy';
4
+ import type { AttentionPolicy } from './types';
5
+
6
+ export interface StoredAttention {
7
+ quiet_mode?: QuietMode;
8
+ quiet?: Partial<AttentionPolicy['quiet']>;
9
+ urgent_words?: string[];
10
+ call_me_at?: number;
11
+ brief_hour?: number;
12
+ wrap_hour?: number;
13
+ notify_scope?: AttentionPolicy['notifyScope'];
14
+ }
15
+ export interface AttentionSettings {
16
+ quiet_mode: QuietMode;
17
+ quiet: AttentionPolicy['quiet'];
18
+ /** Quiet right now (manual mode over schedule). Read-only. */
19
+ quiet_active: boolean;
20
+ urgent_words: string[];
21
+ call_me_at: number;
22
+ /** Local hour of the morning batch and the end-of-day batch. */
23
+ brief_hour: number;
24
+ wrap_hour: number;
25
+ notify_scope: AttentionPolicy['notifyScope'];
26
+ }
27
+
28
+ export const policyFrom = (stored?: StoredAttention): AttentionPolicy => resolveAttentionPolicy({
29
+ ...(stored?.quiet ? { quiet: stored.quiet } : {}), ...(stored?.urgent_words ? { urgentWords: stored.urgent_words } : {}),
30
+ ...(stored?.call_me_at ? { callMeAt: stored.call_me_at } : {}),
31
+ ...(stored?.brief_hour !== undefined ? { brief: { hour: stored.brief_hour } } : {}), ...(stored?.wrap_hour !== undefined ? { wrap: { hour: stored.wrap_hour } } : {}), ...(stored?.notify_scope ? { notifyScope: stored.notify_scope } : {}),
32
+ });
33
+
34
+ export function settingsView(stored: StoredAttention | undefined, now: number): AttentionSettings {
35
+ const policy = policyFrom(stored);
36
+ const mode = stored?.quiet_mode ?? 'off';
37
+ return { quiet_mode: mode, quiet: policy.quiet, quiet_active: isQuiet(now, policy.quiet, mode), urgent_words: policy.urgentWords, call_me_at: policy.callMeAt, brief_hour: policy.brief.hour, wrap_hour: policy.wrap.hour, notify_scope: policy.notifyScope };
38
+ }
39
+
40
+ const bad = (m: string) => new NotifyError(m, 400);
41
+ const hour = (v: unknown, name: string) => { if (typeof v !== 'number' || !Number.isInteger(v) || v < 0 || v > 23) throw bad(`${name} must be an hour from 0 to 23.`); return v; };
42
+
43
+ /** Validates a partial update and merges it into what is stored. Unknown keys are ignored. */
44
+ export function mergeAttention(stored: StoredAttention | undefined, patch: unknown): StoredAttention {
45
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) throw bad('attention must be an object.');
46
+ const p = patch as Record<string, unknown>;
47
+ const out: StoredAttention = { ...stored };
48
+ if (p.quiet_mode !== undefined) {
49
+ if (p.quiet_mode !== 'auto' && p.quiet_mode !== 'on' && p.quiet_mode !== 'off') throw bad('quiet_mode must be auto, on or off.');
50
+ out.quiet_mode = p.quiet_mode;
51
+ }
52
+ if (p.quiet !== undefined) {
53
+ if (!p.quiet || typeof p.quiet !== 'object') throw bad('quiet must be an object.');
54
+ const q = p.quiet as Record<string, unknown>;
55
+ const next: Partial<AttentionPolicy['quiet']> = { ...stored?.quiet };
56
+ if (q.enabled !== undefined) { if (typeof q.enabled !== 'boolean') throw bad('quiet.enabled must be true or false.'); next.enabled = q.enabled; }
57
+ if (q.start !== undefined) next.start = hour(q.start, 'quiet.start');
58
+ if (q.end !== undefined) next.end = hour(q.end, 'quiet.end');
59
+ if (q.timeZone !== undefined) {
60
+ try { new Intl.DateTimeFormat('en-US', { timeZone: String(q.timeZone) }); } catch { throw bad('quiet.timeZone is not a time zone.'); }
61
+ next.timeZone = String(q.timeZone);
62
+ }
63
+ out.quiet = next;
64
+ }
65
+ if (p.urgent_words !== undefined) {
66
+ if (!Array.isArray(p.urgent_words) || p.urgent_words.some((w) => typeof w !== 'string')) throw bad('urgent_words must be a list of words.');
67
+ out.urgent_words = [...new Set((p.urgent_words as string[]).map((w) => w.trim().toLowerCase()).filter(Boolean).map((w) => w.slice(0, 60)))].slice(0, 50);
68
+ }
69
+ if (p.call_me_at !== undefined) {
70
+ if (typeof p.call_me_at !== 'number' || !Number.isInteger(p.call_me_at) || p.call_me_at < 1 || p.call_me_at > 50) throw bad('call_me_at must be a whole number from 1 to 50.');
71
+ out.call_me_at = p.call_me_at;
72
+ }
73
+ if (p.brief_hour !== undefined) out.brief_hour = hour(p.brief_hour, 'brief_hour');
74
+ if (p.wrap_hour !== undefined) out.wrap_hour = hour(p.wrap_hour, 'wrap_hour');
75
+ if (p.notify_scope !== undefined) {
76
+ if (p.notify_scope !== 'decisions' && p.notify_scope !== 'decisions+fleet') throw bad('notify_scope must be decisions or decisions+fleet.');
77
+ out.notify_scope = p.notify_scope;
78
+ }
79
+ return out;
80
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Attention (bd startsim-nd3qa): what needs the person, how urgent it is, and when to interrupt them. Pure data and
3
+ * defaults; the answers still pending with Quinn (quiet hours, call-me threshold, brief and wrap times, whether fleet
4
+ * approvals ping, self-answering routine questions) are fields here, never constants in the logic.
5
+ */
6
+ export type AttentionClass = 'urgent' | 'needs-answer' | 'digest' | 'noise';
7
+ export type AttentionSource = 'fleet' | 'decision' | 'relay';
8
+
9
+ export interface AttentionItem { id: string; text: string; source: AttentionSource; /** The decision id, for an item that is a pending decision (opens its card). */ ref?: string; /** A relay item's choices ("schedule" or "manual"): asked as a choice, not yes/no. */ options?: string[]; /** Who asked, in plain words (a relay item's source project). */ from?: string; /** Where to look at it, when there is somewhere. */ link?: string }
10
+ export interface QueuedItem extends AttentionItem { class: AttentionClass; /** 0-100; urgent 100. Orders the queue and gates call-me. */ importance: number }
11
+
12
+ export interface AttentionPolicy {
13
+ /** Which waiting items count as "needs you": his decisions only, or the fleet's approvals too. */
14
+ notifyScope: 'decisions' | 'decisions+fleet';
15
+ /** Hours (0-23) in the policy time zone; the window may wrap midnight. Urgent items ignore it, everything else waits. */
16
+ quiet: { enabled: boolean; start: number; end: number; timeZone: string };
17
+ /** This many waiting items (urgent included) earns one call-me push. */
18
+ callMeAt: number;
19
+ /** An item must score at least this (see importance.ts) to count toward call-me; urgent always does. 0 counts every waiting item. */
20
+ callMeMinImportance: number;
21
+ /** Case-insensitive RegExp sources for what raises an item's importance: money, outward-facing actions, only he can provide. */
22
+ moneyPatterns: string[];
23
+ outwardPatterns: string[];
24
+ onlyYouPatterns: string[];
25
+ importanceWeights: { money: number; outward: number; onlyYou: number };
26
+ /** Daily rhythm (slice 5 reads these). */
27
+ brief: { hour: number };
28
+ wrap: { hour: number };
29
+ /** Answer continue / proceed questions without asking him (never an urgent one). */
30
+ selfAnswerRoutine: boolean;
31
+ /** Case-insensitive RegExp sources: a pending decision matching one (and not urgent) is answered "yes, continue" for him. */
32
+ routinePatterns: string[];
33
+ /** Case-insensitive RegExp sources. A line matching an urgent pattern is urgent; one matching a noise pattern is noise (urgent wins). */
34
+ urgentPatterns: string[];
35
+ noisePatterns: string[];
36
+ /** Plain words the person adds (no regex): a line containing one is urgent. */
37
+ urgentWords: string[];
38
+ /** How many items one briefing asks at a time (a short stand-up). */
39
+ briefBatch: number;
40
+ /** Matches wait for the daily brief instead of asking now (optional asks, items on hold). Urgent and noise are decided first. */
41
+ digestPatterns: string[];
42
+ }
43
+
44
+ export type AttentionPolicyInput = Partial<Omit<AttentionPolicy, 'quiet' | 'brief' | 'wrap' | 'importanceWeights'>> & {
45
+ quiet?: Partial<AttentionPolicy['quiet']>; brief?: Partial<AttentionPolicy['brief']>; wrap?: Partial<AttentionPolicy['wrap']>; importanceWeights?: Partial<AttentionPolicy['importanceWeights']>;
46
+ };
47
+
48
+ export const ATTENTION_DEFAULTS: AttentionPolicy = {
49
+ notifyScope: 'decisions+fleet',
50
+ quiet: { enabled: true, start: 22, end: 7, timeZone: 'America/Los_Angeles' },
51
+ callMeAt: 3,
52
+ callMeMinImportance: 40,
53
+ moneyPatterns: ['\\$\\s?\\d', '\\b(pay|paid|payment|invoice|refund|charge[ds]?|billing|bill|subscription|stripe|budget|spend|price|pricing|purchase|buy|wire|payroll|tax(es)?)\\b'],
54
+ outwardPatterns: ['\\b(send|sends|publish|post|announce|launch|ship|deploy|promote|release|merge to main|go live|email|emails|customers?|clients?|investors?|press|tweet|public)\\b'],
55
+ onlyYouPatterns: ['\\b(your|you)\\b.*\\b(approval|approve|sign|signature|password|key|token|credential|login|decision|decide|call)\\b', '\\b(approve|sign off|sign-off|need(s)? (you|him)|only (you|he) can)\\b', '\\b(api key|password|token|credentials?)\\b'],
56
+ importanceWeights: { money: 30, outward: 25, onlyYou: 25 },
57
+ brief: { hour: 8 },
58
+ wrap: { hour: 18 },
59
+ selfAnswerRoutine: true,
60
+ routinePatterns: ['\\b(should|shall|can|may) (we|i) (continue|proceed|keep going|go on)\\b', '\\b(ok|okay) to (continue|proceed)\\b', '^\\s*(continue|proceed)\\?', "\\b(i am|i'm) going to\\b.*\\b(unless|if) you\\b"],
61
+ urgentPatterns: ['\\burgent\\b', '\\basap\\b', '\\boutage\\b', '\\bincident\\b', '\\b(prod|production)\\b.*\\bdown\\b', '\\bdown\\b.*\\b(prod|production)\\b', '\\bpayment (failed|failing)\\b', '\\b(security|breach|leaked?)\\b', '\\bexpires? (today|tonight|in \\d+ ?(m|min|minutes|h|hours?))\\b', '\\bdeadline (today|tonight)\\b'],
62
+ urgentWords: [],
63
+ briefBatch: 5,
64
+ digestPatterns: ['\\boptional\\b', '\\bhold\\b', '\\bstays? paused\\b', '\\bwhen (he|you) (is|are)? ?ready\\b'],
65
+ noisePatterns: ['^\\s*fyi\\b', '\\bno action (needed|required)\\b', '\\bnothing (needed|required) from you\\b', '\\bfor your information\\b', '\\b(should|shall|can|may) (we|i) (continue|proceed|keep going|go on)\\b', '\\b(ok|okay) to (continue|proceed)\\b', '^\\s*(continue|proceed)\\?'],
66
+ };
67
+
68
+ export interface NeedsYouQueue {
69
+ items: QueuedItem[];
70
+ counts: Record<AttentionClass, number>;
71
+ /** Enough are waiting that a call (Talk, batched) beats reading them one by one. */
72
+ callMe: boolean;
73
+ /** Waiting items that count toward the call-me threshold (urgent + needs-answer). */
74
+ waiting: number;
75
+ }
@@ -16,7 +16,7 @@ export class ConverseClientError extends Error {
16
16
  }
17
17
 
18
18
  export interface ConverseClient {
19
- turn(input: { audio?: Blob; text?: string; conversationId?: string; turnId?: string; timeZone?: string }): Promise<ConverseTurnResult>;
19
+ turn(input: { audio?: Blob; text?: string; briefing?: 'start'; conversationId?: string; turnId?: string; timeZone?: string }): Promise<ConverseTurnResult>;
20
20
  end(conversationId: string): Promise<ConverseEndResult>;
21
21
  /** The thread from turn `after` + 1 on: how a page finds out the relay wrote into it. */
22
22
  thread(conversationId: string, after: number): Promise<ConverseThread>;
@@ -47,10 +47,11 @@ export function createConverseClient(options: {
47
47
  }
48
48
 
49
49
  return {
50
- async turn({ audio, text, conversationId, turnId, timeZone }) {
50
+ async turn({ audio, text, briefing, conversationId, turnId, timeZone }) {
51
51
  const body = new FormData();
52
52
  if (audio) body.append('audio', audio, 'turn');
53
53
  if (text) body.append('text', text);
54
+ if (briefing) body.append('briefing', briefing);
54
55
  if (conversationId) body.append('conversation_id', conversationId);
55
56
  if (turnId) body.append('turn_id', turnId);
56
57
  body.append('timeZone', timeZone || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC');
@@ -44,17 +44,19 @@ const resultOf = (id: string, turn: ConverseTurn): ConverseTurnResult => ({
44
44
  audio_reason: turn.assistant.audio_ref ? null : (turn.assistant.audio_reason ?? 'no audio was produced'),
45
45
  ...(turn.intent ? { intent: turn.intent } : {}),
46
46
  ...(turn.sources?.length ? { sources: turn.sources } : {}),
47
+ ...(turn.attn ? { briefing: turn.attn } : {}),
47
48
  });
48
49
 
49
50
  function validate(req: ConverseTurnRequest) {
50
51
  if (req.conversationId !== undefined && !CLIENT_ID.test(req.conversationId)) throw new ConverseError('That conversation id is not valid.', 400);
51
52
  if (req.turnId !== undefined && !CLIENT_ID.test(req.turnId)) throw new ConverseError('turn_id must be 8-64 letters, digits, - or _.', 400);
52
- if (!req.text?.trim() && !req.audio) throw new ConverseError('Send what was said: audio or text.', 400);
53
+ if (!req.text?.trim() && !req.audio && req.briefing !== 'start') throw new ConverseError('Send what was said: audio or text.', 400);
53
54
  if (req.audio && req.audio.audio.byteLength > MAX_CONVERSE_AUDIO_BYTES) throw new ConverseError('That recording is too long for one turn.', 413);
54
55
  }
55
56
 
56
57
  export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRequest): Promise<ConverseTurnResult> {
57
58
  validate(req);
59
+ if (req.briefing === 'start' && !deps.attentionRun) throw new ConverseError('Send what was said: audio or text.', 400);
58
60
  const now = (deps.now ?? Date.now)();
59
61
  const store = deps.store ?? createEntityConversationStore(deps.http, deps.ownerSub);
60
62
  const newId = deps.newId ?? (() => crypto.randomUUID());
@@ -88,11 +90,21 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
88
90
  try {
89
91
  utterance = (await deps.transcribe({ audio: req.audio.audio, mimeType: req.audio.mimeType, hints })).trim();
90
92
  } catch (error) {
93
+ if (error instanceof Error && /no speech providers|provider is not configured|not configured/i.test(error.message)) {
94
+ throw new ConverseError('Voice is not set up on this server. You can type instead.', 503, 'speech_unavailable');
95
+ }
91
96
  throw new ConverseError(`I could not make out the recording: ${error instanceof Error ? error.message : 'transcription failed'}`, 502, 'transcription_failed');
92
97
  }
93
98
  }
94
99
  lap('stt');
95
100
 
101
+ // 1b. The needs-you briefing: the assistant asks (start) or takes his answer to the current question.
102
+ let walk: Awaited<ReturnType<NonNullable<ConverseDeps['attentionRun']>['start']>> | null = null;
103
+ if (deps.attentionRun) {
104
+ if (req.briefing === 'start') walk = await deps.attentionRun.start(conversationId);
105
+ else if (utterance) walk = await deps.attentionRun.answer(conversationId, utterance);
106
+ }
107
+
96
108
  // 2. Answer.
97
109
  let replyText = NOT_HEARD;
98
110
  let did: string[] | undefined;
@@ -105,7 +117,10 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
105
117
  let briefing = record?.briefing;
106
118
  let context = record?.context;
107
119
  let pending: ConversationRecord['pending'];
108
- if (utterance) {
120
+ if (walk) {
121
+ replyText = walk.text;
122
+ intent = 'briefing';
123
+ } else if (utterance) {
109
124
  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);
110
125
  const history = lines.slice(-(deps.historyLines ?? DEFAULT_HISTORY_LINES));
111
126
  try {
@@ -169,7 +184,7 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
169
184
  lap('tts');
170
185
 
171
186
  // 4. Save.
172
- const turn: ConverseTurn = { n, turn_id: turnId, at: new Date(now).toISOString(), user, assistant, ...(did ? { did } : {}), ...(forRelay ? { for_relay: true } : {}), ...(intent ? { intent } : {}), ...(sources?.length ? { sources } : {}) };
187
+ const turn: ConverseTurn = { n, turn_id: turnId, at: new Date(now).toISOString(), user, assistant, ...(did ? { did } : {}), ...(forRelay ? { for_relay: true } : {}), ...(intent ? { intent } : {}), ...(sources?.length ? { sources } : {}), ...(walk ? { attn: { active: walk.active, index: walk.index, of: walk.of } } : {}) };
173
188
  const base = endedRecord ?? record;
174
189
  const startedAt = base?.startedAt ?? turn.at;
175
190
  await store.save({