@startsimpli/integrations 0.2.158 → 0.2.162
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +6 -6
- package/src/__tests__/briefing-weekly.test.ts +80 -0
- package/src/__tests__/corpus-ask-items.test.ts +108 -0
- package/src/__tests__/corpus-planning.test.tsx +31 -0
- package/src/__tests__/home-brief.test.tsx +10 -0
- package/src/__tests__/home-needs-your-call.test.tsx +68 -0
- package/src/__tests__/measure/notes.ts +28 -0
- package/src/__tests__/measure/voice-notes.measure.test.ts +51 -0
- package/src/__tests__/needs-your-call.test.tsx +151 -0
- package/src/__tests__/question-evidence.test.ts +82 -0
- package/src/__tests__/question-inbox.test.ts +51 -0
- package/src/__tests__/question-voice.test.ts +18 -0
- package/src/components/index.ts +1 -0
- package/src/components/pages/AskPage.tsx +12 -2
- package/src/components/pages/PlanningPage.tsx +14 -4
- package/src/components/pages/home/BriefCard.tsx +31 -12
- package/src/components/pages/home/CompactItemRow.tsx +12 -2
- package/src/components/pages/home/DueAcrossProjects.tsx +4 -2
- package/src/components/pages/home/HomeBriefPage.tsx +32 -3
- package/src/components/pages/questions/NeedsYourCall.tsx +128 -0
- package/src/components/pages/questions/QuestionRow.tsx +78 -0
- package/src/components/pages/questions/index.ts +3 -0
- package/src/components/pages/questions/types.ts +36 -0
- package/src/corpus/ask-items-intent.ts +75 -0
- package/src/corpus/ask-items.ts +100 -0
- package/src/corpus/ask.ts +48 -5
- package/src/corpus/briefing/generate-weekly.ts +89 -0
- package/src/corpus/briefing/index.ts +5 -1
- package/src/corpus/briefing/respond.ts +11 -3
- package/src/corpus/briefing/types.ts +2 -0
- package/src/corpus/briefing/weekly.ts +155 -0
- package/src/corpus/index.ts +3 -0
- package/src/corpus/llm.ts +3 -2
- package/src/corpus/questions/evidence.ts +65 -0
- package/src/corpus/questions/inbox.ts +108 -0
- package/src/corpus/questions/index.ts +6 -1
- package/src/corpus/questions/items.ts +21 -0
- package/src/corpus/questions/learn.ts +16 -0
- package/src/corpus/questions/sync.ts +7 -3
- package/src/corpus/questions/types.ts +5 -1
- package/src/corpus/questions/voice.ts +23 -4
- package/src/corpus/types.ts +4 -0
- package/src/corpus/voice.ts +5 -2
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ONE QUESTION: the to-do it is about, the question, what Tandem is assuming
|
|
3
|
+
* (quiet, not a warning), answer chips (a tap answers), "Skip it", and a free
|
|
4
|
+
* answer for anything the chips do not say. Presentational: the list owns the saving.
|
|
5
|
+
*/
|
|
6
|
+
import * as React from 'react';
|
|
7
|
+
|
|
8
|
+
import { assumedLabel, chipsFor, readTypedAnswer, type ChipContext } from '../../../corpus/questions';
|
|
9
|
+
import type { OpenQuestion, QuestionAnswer } from '../../../corpus/questions';
|
|
10
|
+
|
|
11
|
+
const CHIP = 'inline-flex min-h-9 items-center rounded-full border border-gray-300 bg-white px-3 py-1 text-sm text-gray-800 hover:bg-gray-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500';
|
|
12
|
+
const KEEP = 'inline-flex min-h-9 items-center rounded-full border border-blue-200 bg-blue-50 px-3 py-1 text-sm text-blue-900 hover:bg-blue-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500';
|
|
13
|
+
|
|
14
|
+
export interface QuestionRowProps {
|
|
15
|
+
question: OpenQuestion;
|
|
16
|
+
title: string;
|
|
17
|
+
chipContext: ChipContext;
|
|
18
|
+
now: number;
|
|
19
|
+
onAnswer: (q: OpenQuestion, answer: QuestionAnswer) => void;
|
|
20
|
+
onSkip: (q: OpenQuestion) => void;
|
|
21
|
+
onOpenItem?: (itemId: string) => void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function QuestionRow({ question: q, title, chipContext, now, onAnswer, onSkip, onOpenItem }: QuestionRowProps) {
|
|
25
|
+
const [typing, setTyping] = React.useState(false);
|
|
26
|
+
const [text, setText] = React.useState('');
|
|
27
|
+
const [hint, setHint] = React.useState('');
|
|
28
|
+
const chips = chipsFor(q, chipContext);
|
|
29
|
+
const guess = assumedLabel(q, chipContext);
|
|
30
|
+
const inputId = `q-${q.id}-free`;
|
|
31
|
+
|
|
32
|
+
const submit = (event: React.FormEvent) => {
|
|
33
|
+
event.preventDefault();
|
|
34
|
+
if (!text.trim()) return;
|
|
35
|
+
const read = readTypedAnswer(q, text, { now, timeZone: chipContext.timeZone, options: chipContext.options, labels: chipContext.labels });
|
|
36
|
+
if (read.kind === 'answer') onAnswer(q, read.answer);
|
|
37
|
+
else if (read.kind === 'skip') onSkip(q);
|
|
38
|
+
else setHint(read.message);
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
return (
|
|
42
|
+
<li className="space-y-2 border-b border-gray-100 py-3 last:border-b-0" data-testid="question-row">
|
|
43
|
+
{onOpenItem ? (
|
|
44
|
+
<button type="button" className="block max-w-full truncate text-left text-sm font-medium text-gray-900 hover:underline" onClick={() => onOpenItem(q.itemId)}>{title}</button>
|
|
45
|
+
) : <p className="truncate text-sm font-medium text-gray-900">{title}</p>}
|
|
46
|
+
<p className="text-sm text-gray-700">{q.question}</p>
|
|
47
|
+
{guess ? (
|
|
48
|
+
<p className="text-xs text-gray-500" title={q.assumed?.reason || undefined}>For now I am going with {guess}.</p>
|
|
49
|
+
) : null}
|
|
50
|
+
<div role="group" aria-label={`Answers for ${title}`} className="flex flex-wrap items-center gap-2">
|
|
51
|
+
{chips.map((chip) => (
|
|
52
|
+
<button
|
|
53
|
+
key={chip.value || 'none'} type="button" className={chip.assumed ? KEEP : CHIP} title={chip.reason || undefined}
|
|
54
|
+
onClick={() => onAnswer(q, { value: chip.value, label: chip.label })}
|
|
55
|
+
>
|
|
56
|
+
{chip.assumed ? `Keep ${chip.label}` : chip.label}
|
|
57
|
+
</button>
|
|
58
|
+
))}
|
|
59
|
+
<button type="button" className="min-h-9 px-2 text-sm text-gray-600 underline" aria-expanded={typing} onClick={() => setTyping(!typing)}>
|
|
60
|
+
{chips.length ? 'Something else' : 'Answer'}
|
|
61
|
+
</button>
|
|
62
|
+
<button type="button" className="min-h-9 px-2 text-sm text-gray-500 underline" onClick={() => onSkip(q)}>Skip it</button>
|
|
63
|
+
</div>
|
|
64
|
+
{typing ? (
|
|
65
|
+
<form className="flex flex-wrap items-center gap-2" onSubmit={submit}>
|
|
66
|
+
<label htmlFor={inputId} className="sr-only">Your answer for {title}</label>
|
|
67
|
+
<input
|
|
68
|
+
id={inputId} value={text} onChange={(e) => { setText(e.target.value); setHint(''); }}
|
|
69
|
+
placeholder={q.kind === 'due_date' ? 'A day, like next Friday' : 'Your answer'}
|
|
70
|
+
className="min-h-9 min-w-0 flex-1 rounded-md border border-gray-300 px-3 text-sm"
|
|
71
|
+
/>
|
|
72
|
+
<button type="submit" className={CHIP}>Save</button>
|
|
73
|
+
{hint ? <p className="w-full text-xs text-gray-600" role="status">{hint}</p> : null}
|
|
74
|
+
</form>
|
|
75
|
+
) : null}
|
|
76
|
+
</li>
|
|
77
|
+
);
|
|
78
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { AnswerOption, OpenQuestion, QuestionAnswer } from '../../../corpus/questions';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* What the "Needs your call" card needs from its host (bd startsim-tmrvi.7). A tenant app wires it
|
|
5
|
+
* to its own routes (GET and POST /corpus/questions, and the skip press); nothing here
|
|
6
|
+
* knows a URL, so the card is not tied to one app.
|
|
7
|
+
*/
|
|
8
|
+
export interface NeedsYourCallApi {
|
|
9
|
+
/** The signed-in person's open questions, best first. Private items only ever arrive for their owner. */
|
|
10
|
+
list(): Promise<OpenQuestion[]>;
|
|
11
|
+
/** Save one answer. Rejects when it could not be saved. */
|
|
12
|
+
answer(question: OpenQuestion, answer: QuestionAnswer): Promise<void>;
|
|
13
|
+
/** Leave one for later. Rejects when it could not be saved. */
|
|
14
|
+
skip(question: OpenQuestion): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface NeedsYourCallProps {
|
|
18
|
+
api: NeedsYourCallApi;
|
|
19
|
+
/** The title of the to-do a question is about; unknown ids read "A to-do". */
|
|
20
|
+
itemTitle?: (itemId: string) => string | undefined;
|
|
21
|
+
/** Project id to name, for project chips. */
|
|
22
|
+
projectNames?: Record<string, string>;
|
|
23
|
+
/** Extra choices for a question (a team, an owner) when the host can name them. */
|
|
24
|
+
options?: (question: OpenQuestion) => Promise<AnswerOption[]>;
|
|
25
|
+
timeZone?: string;
|
|
26
|
+
now?: number;
|
|
27
|
+
/** How many to show before "Show more". Default 5. */
|
|
28
|
+
pageSize?: number;
|
|
29
|
+
/** Fires the moment an answer is tapped, before it is saved: update the to-do in place. */
|
|
30
|
+
onApplied?: (question: OpenQuestion, answer: QuestionAnswer) => void;
|
|
31
|
+
/** The save failed: undo whatever `onApplied` showed. */
|
|
32
|
+
onReverted?: (question: OpenQuestion) => void;
|
|
33
|
+
/** The questions still open, whenever they change (to mark guessed values on the to-do rows). */
|
|
34
|
+
onOpenQuestions?: (questions: OpenQuestion[]) => void;
|
|
35
|
+
onOpenItem?: (itemId: string) => void;
|
|
36
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What an Ask question wants from the TRACKED ITEMS, decided in code (bd startsim-tmrvi).
|
|
3
|
+
*
|
|
4
|
+
* PURE: `now` and the reader's IANA zone come in. "What is due Friday" and "what
|
|
5
|
+
* is slipping" are questions about dates and states, which a keyword ranker over
|
|
6
|
+
* documents cannot answer and a model should not be left to compute: the window is
|
|
7
|
+
* worked out here, the matching items are selected here, and the model only phrases
|
|
8
|
+
* what it was handed.
|
|
9
|
+
*/
|
|
10
|
+
import { localDate } from './today';
|
|
11
|
+
|
|
12
|
+
export type ItemFocus = 'slipping' | 'due' | 'committed' | 'status';
|
|
13
|
+
|
|
14
|
+
export interface ItemIntent {
|
|
15
|
+
focus: ItemFocus;
|
|
16
|
+
/** Inclusive calendar days in the reader's zone. Absent = no date window. */
|
|
17
|
+
from?: string;
|
|
18
|
+
to?: string;
|
|
19
|
+
/** "I", "my": only the reader's own items. */
|
|
20
|
+
mine: boolean;
|
|
21
|
+
/** Today in the reader's zone, handed to the model so "overdue" has a reference. */
|
|
22
|
+
today: string;
|
|
23
|
+
/** What the window means, in words ("this week (2026-11-09 to 2026-11-15)"). */
|
|
24
|
+
windowLabel?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
|
|
28
|
+
const ITEM_WORDS = /\b(commit(?:ted|ment|ments)?|promis(?:ed|e)|owe|due|deadline|deadlines|slipp(?:ing|ed)|behind|overdue|late|at risk|blocked|to-?dos?|tasks?|items?|status|on my plate|open|in progress|linear|assigned|owner)\b/i;
|
|
29
|
+
|
|
30
|
+
const addDays = (day: string, n: number): string => {
|
|
31
|
+
const d = new Date(`${day}T00:00:00Z`);
|
|
32
|
+
d.setUTCDate(d.getUTCDate() + n);
|
|
33
|
+
return d.toISOString().slice(0, 10);
|
|
34
|
+
};
|
|
35
|
+
const weekdayOf = (day: string): number => new Date(`${day}T00:00:00Z`).getUTCDay();
|
|
36
|
+
|
|
37
|
+
/** Monday-first week containing `day`. */
|
|
38
|
+
function weekOf(day: string): { from: string; to: string } {
|
|
39
|
+
const offset = (weekdayOf(day) + 6) % 7;
|
|
40
|
+
const from = addDays(day, -offset);
|
|
41
|
+
return { from, to: addDays(from, 6) };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The intent, or null when the question is not about tracked items at all. */
|
|
45
|
+
export function itemIntent(question: string, now: number, timeZone = 'UTC'): ItemIntent | null {
|
|
46
|
+
const q = question.toLowerCase();
|
|
47
|
+
if (!ITEM_WORDS.test(q)) return null;
|
|
48
|
+
const today = localDate(now, timeZone);
|
|
49
|
+
const mine = /\b(i|i'm|i've|my|me|mine)\b/.test(q);
|
|
50
|
+
|
|
51
|
+
let focus: ItemFocus = 'status';
|
|
52
|
+
if (/\b(slipp(?:ing|ed)|behind|overdue|late|at risk|missed)\b/.test(q)) focus = 'slipping';
|
|
53
|
+
else if (/\b(commit(?:ted|ment|ments)?|promis(?:ed|e)|owe)\b/.test(q)) focus = 'committed';
|
|
54
|
+
else if (/\b(due|deadline|deadlines)\b/.test(q)) focus = 'due';
|
|
55
|
+
|
|
56
|
+
let from: string | undefined;
|
|
57
|
+
let to: string | undefined;
|
|
58
|
+
let windowLabel: string | undefined;
|
|
59
|
+
const set = (a: string, b: string, label: string) => { from = a; to = b; windowLabel = `${label} (${a === b ? a : `${a} to ${b}`})`; };
|
|
60
|
+
|
|
61
|
+
const named = WEEKDAYS.find((w) => new RegExp(`\\b${w}\\b`).test(q));
|
|
62
|
+
if (/\bnext week\b/.test(q)) { const w = weekOf(addDays(today, 7)); set(w.from, w.to, 'next week'); }
|
|
63
|
+
else if (/\blast week\b/.test(q)) { const w = weekOf(addDays(today, -7)); set(w.from, w.to, 'last week'); }
|
|
64
|
+
else if (/\bthis week\b|\bthe week\b/.test(q)) { const w = weekOf(today); set(w.from, w.to, 'this week'); }
|
|
65
|
+
else if (/\btomorrow\b/.test(q)) set(addDays(today, 1), addDays(today, 1), 'tomorrow');
|
|
66
|
+
else if (/\btoday\b/.test(q)) set(today, today, 'today');
|
|
67
|
+
else if (/\byesterday\b/.test(q)) set(addDays(today, -1), addDays(today, -1), 'yesterday');
|
|
68
|
+
else if (named) {
|
|
69
|
+
// The NEXT such weekday, today included: "due Friday" on a Friday means today.
|
|
70
|
+
const delta = (WEEKDAYS.indexOf(named) - weekdayOf(today) + 7) % 7;
|
|
71
|
+
const day = addDays(today, delta);
|
|
72
|
+
set(day, day, named[0].toUpperCase() + named.slice(1));
|
|
73
|
+
}
|
|
74
|
+
return { focus, from, to, mine, today, ...(windowLabel ? { windowLabel } : {}) };
|
|
75
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tracked items as ANSWERABLE, CITABLE records (bd startsim-tmrvi).
|
|
3
|
+
*
|
|
4
|
+
* Ask used to retrieve documents only, so "what did I commit to this week" had no
|
|
5
|
+
* path to the item rows that actually hold status, due date, owner and Linear
|
|
6
|
+
* state. An item becomes a `SourceDocument` here (like a money event does) so the
|
|
7
|
+
* existing citation resolver traces the answer to the exact item record — the id
|
|
8
|
+
* is `item:<id>`, which can never collide with a document id.
|
|
9
|
+
*/
|
|
10
|
+
import { itemIntent, type ItemIntent } from './ask-items-intent';
|
|
11
|
+
import { dueDay } from './today';
|
|
12
|
+
import type { Commitment, CommitmentApi, CorpusScope, RetrievedDocument, SourceDocument } from './types';
|
|
13
|
+
import { isInScope } from './retrieval';
|
|
14
|
+
|
|
15
|
+
export const ITEM_ID_PREFIX = 'item:';
|
|
16
|
+
/** The item id behind a cited record id, or null when it is a document. */
|
|
17
|
+
export const itemIdOf = (documentId: string): string | null =>
|
|
18
|
+
documentId.startsWith(ITEM_ID_PREFIX) ? documentId.slice(ITEM_ID_PREFIX.length) : null;
|
|
19
|
+
export const ITEM_SUBTYPE = 'tracked_item';
|
|
20
|
+
const FINISHED = new Set(['done', 'dropped']);
|
|
21
|
+
const LINEAR_FINISHED = new Set(['completed', 'canceled', 'cancelled']);
|
|
22
|
+
|
|
23
|
+
export interface ItemContext {
|
|
24
|
+
now: number;
|
|
25
|
+
timeZone?: string;
|
|
26
|
+
/** The reader's member id, for "my". */
|
|
27
|
+
ownerSub?: string;
|
|
28
|
+
/** Project names by focus id, when the caller has them. */
|
|
29
|
+
focusNames?: Record<string, string>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** One item as a record the model can read and the screen can cite. */
|
|
33
|
+
export function itemAsDocument(item: Commitment, ctx: ItemContext): SourceDocument {
|
|
34
|
+
const zone = ctx.timeZone ?? 'UTC';
|
|
35
|
+
const due = dueDay(item.dueAt, zone);
|
|
36
|
+
const project = item.focusId ? ctx.focusNames?.[item.focusId] : undefined;
|
|
37
|
+
const lines = [
|
|
38
|
+
`Status: ${item.status}${item.statusReason ? ` (${item.statusReason})` : ''}`,
|
|
39
|
+
`Due: ${due ?? 'no date'}`,
|
|
40
|
+
`Owner: ${item.ownerName ?? 'unassigned'}`,
|
|
41
|
+
`Project: ${project ?? (item.destination === 'personal' ? 'Personal' : item.focusId ? 'filed' : 'unfiled')}`,
|
|
42
|
+
item.priority !== undefined ? `Priority: ${item.priority} (0 critical .. 4 backlog)` : '',
|
|
43
|
+
item.sync?.key ? `Linear: ${item.sync.key}${item.sync.stateName ? ` — ${item.sync.stateName}` : ''}` : '',
|
|
44
|
+
item.firstSeenAt ? `First said: ${item.firstSeenAt.slice(0, 10)}` : '',
|
|
45
|
+
item.detail ? `Detail: ${item.detail}` : '',
|
|
46
|
+
].filter(Boolean);
|
|
47
|
+
return {
|
|
48
|
+
id: `${ITEM_ID_PREFIX}${item.externalId}`,
|
|
49
|
+
title: item.title,
|
|
50
|
+
body: lines.join('\n'),
|
|
51
|
+
sections: [],
|
|
52
|
+
occurredAt: item.firstSeenAt,
|
|
53
|
+
source: item.source,
|
|
54
|
+
sourceLabel: 'Tracked item',
|
|
55
|
+
subtype: ITEM_SUBTYPE,
|
|
56
|
+
sourceRef: item.id,
|
|
57
|
+
participants: [],
|
|
58
|
+
scope: item.scope,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Which of `items` the intent asks about, in the order worth reading. Pure. */
|
|
63
|
+
export function selectItems(items: Commitment[], intent: ItemIntent, ctx: ItemContext): Commitment[] {
|
|
64
|
+
const zone = ctx.timeZone ?? 'UTC';
|
|
65
|
+
const inWindow = (day: string | null) => Boolean(day && (!intent.from || day >= intent.from) && (!intent.to || day <= intent.to));
|
|
66
|
+
const finished = (i: Commitment) => FINISHED.has(i.status) || LINEAR_FINISHED.has((i.sync?.stateName ?? '').toLowerCase());
|
|
67
|
+
const picked = items.filter((item) => {
|
|
68
|
+
if (intent.mine && ctx.ownerSub && item.ownerSub !== ctx.ownerSub && !item.ownerSubs?.includes(ctx.ownerSub)) return false;
|
|
69
|
+
const due = dueDay(item.dueAt, zone);
|
|
70
|
+
const said = item.firstSeenAt ? dueDay(item.firstSeenAt, zone) : null;
|
|
71
|
+
switch (intent.focus) {
|
|
72
|
+
case 'slipping': return !finished(item) && (item.status === 'blocked' || Boolean(due && due < intent.today));
|
|
73
|
+
case 'due': return intent.from ? inWindow(due) : Boolean(due) && !finished(item);
|
|
74
|
+
case 'committed': return intent.from ? inWindow(due) || inWindow(said) : !finished(item);
|
|
75
|
+
default: return intent.from ? inWindow(due) || inWindow(said) : !finished(item);
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
return picked.sort((a, b) =>
|
|
79
|
+
(dueDay(a.dueAt, zone) ?? '9999').localeCompare(dueDay(b.dueAt, zone) ?? '9999') || (a.priority ?? 9) - (b.priority ?? 9));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Items for a question: read, scope-check, select, convert. Empty when it is not an item question. */
|
|
83
|
+
export async function retrieveItems(
|
|
84
|
+
question: string,
|
|
85
|
+
api: Pick<CommitmentApi, 'listCommitments'> | undefined,
|
|
86
|
+
scope: CorpusScope,
|
|
87
|
+
ctx: ItemContext,
|
|
88
|
+
limit: number,
|
|
89
|
+
): Promise<{ intent: ItemIntent | null; retrieved: RetrievedDocument[]; matched: number }> {
|
|
90
|
+
const intent = itemIntent(question, ctx.now, ctx.timeZone);
|
|
91
|
+
if (!intent || !api) return { intent: null, retrieved: [], matched: 0 };
|
|
92
|
+
const page = await api.listCommitments({ pageSize: 200, sort: 'due', withFocus: true }).catch(() => null);
|
|
93
|
+
if (!page) return { intent, retrieved: [], matched: 0 };
|
|
94
|
+
const selected = selectItems(page.results.filter((item) => isInScope(item, scope)), intent, ctx);
|
|
95
|
+
const retrieved = selected.slice(0, limit).map((item): RetrievedDocument => {
|
|
96
|
+
const document = itemAsDocument(item, ctx);
|
|
97
|
+
return { document, score: 1, matchedTerms: [], snippet: document.body.split('\n').slice(0, 2).join(' · ') };
|
|
98
|
+
});
|
|
99
|
+
return { intent, retrieved, matched: selected.length };
|
|
100
|
+
}
|
package/src/corpus/ask.ts
CHANGED
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
* cannot trust with a contract. A model that cites a document id it was never
|
|
19
19
|
* given has invented a source, and the only safe rendering of that is to say so.
|
|
20
20
|
*/
|
|
21
|
+
import { retrieveItems } from './ask-items';
|
|
21
22
|
import { moneyEventAsDocument } from './entities';
|
|
22
23
|
import { retrieveForQuestion, searchTermFor } from './retrieval';
|
|
23
24
|
import { documentText } from './text';
|
|
@@ -26,6 +27,7 @@ import type {
|
|
|
26
27
|
AskRequest,
|
|
27
28
|
AskResult,
|
|
28
29
|
Citation,
|
|
30
|
+
CommitmentApi,
|
|
29
31
|
CorpusApi,
|
|
30
32
|
CorpusLlm,
|
|
31
33
|
PromptDocument,
|
|
@@ -43,12 +45,21 @@ export interface AskCorpusOptions {
|
|
|
43
45
|
maxCharsPerDocument?: number;
|
|
44
46
|
/** Injectable clock for the recency prior. */
|
|
45
47
|
now?: number;
|
|
48
|
+
/** How many tracked items an item question may put in front of the model. */
|
|
49
|
+
itemLimit?: number;
|
|
50
|
+
/** The reader's IANA zone, so "Friday" and "overdue" mean THEIR calendar. */
|
|
51
|
+
timeZone?: string;
|
|
52
|
+
/** The reader's member id, for "what did I commit to". */
|
|
53
|
+
ownerSub?: string;
|
|
54
|
+
/** Project names by focus id, for the item records. */
|
|
55
|
+
focusNames?: Record<string, string>;
|
|
46
56
|
}
|
|
47
57
|
|
|
48
|
-
const DEFAULTS
|
|
58
|
+
const DEFAULTS = {
|
|
49
59
|
candidateLimit: 200,
|
|
50
60
|
contextLimit: 8,
|
|
51
61
|
maxCharsPerDocument: 6000,
|
|
62
|
+
itemLimit: 30,
|
|
52
63
|
};
|
|
53
64
|
|
|
54
65
|
/**
|
|
@@ -75,6 +86,7 @@ function systemPrompt(mode: AskRequest['mode']): string {
|
|
|
75
86
|
'You answer questions about a company using only that company\'s own records.',
|
|
76
87
|
...shared,
|
|
77
88
|
'Be specific and short. Prefer naming the record and the date over hedging.',
|
|
89
|
+
'Documents whose id starts with "item:" are TRACKED ITEMS (to-dos): their Status, Due, Owner, Project and Linear lines are the facts. Answer from those lines exactly, compare dates against the "today" given, and cite each item you mention by its id.',
|
|
78
90
|
'A document may list "withheld_from_this_reader". Those parts were deliberately not shown to you: never claim something was not said or did not happen on the basis of a document that lists them — say the record is partly withheld instead.',
|
|
79
91
|
].join('\n');
|
|
80
92
|
}
|
|
@@ -84,6 +96,7 @@ export function buildAnswerRequest(
|
|
|
84
96
|
request: AskRequest,
|
|
85
97
|
retrieved: RetrievedDocument[],
|
|
86
98
|
maxChars: number,
|
|
99
|
+
extra: { today?: string; itemWindow?: string } = {},
|
|
87
100
|
): AnswerRequest {
|
|
88
101
|
const documents: PromptDocument[] = retrieved.map(({ document }) => ({
|
|
89
102
|
id: document.id,
|
|
@@ -102,6 +115,8 @@ export function buildAnswerRequest(
|
|
|
102
115
|
mode: request.mode,
|
|
103
116
|
instructions: request.instructions,
|
|
104
117
|
documents,
|
|
118
|
+
...(extra.today ? { today: extra.today } : {}),
|
|
119
|
+
...(extra.itemWindow ? { itemWindow: extra.itemWindow } : {}),
|
|
105
120
|
};
|
|
106
121
|
}
|
|
107
122
|
|
|
@@ -147,6 +162,7 @@ export function renderAnswerPrompt(input: AnswerRequest): string {
|
|
|
147
162
|
? `DRAFT REQUEST:\n${input.question}`
|
|
148
163
|
: `QUESTION:\n${input.question}`;
|
|
149
164
|
return [
|
|
165
|
+
input.today ? `TODAY: ${input.today}${input.itemWindow ? ` · asked about ${input.itemWindow}` : ''}` : '',
|
|
150
166
|
`DOCUMENTS (${input.documents.length}):`,
|
|
151
167
|
blocks.join('\n\n'),
|
|
152
168
|
'',
|
|
@@ -333,10 +349,10 @@ function noEvidenceCopy(total: number): string {
|
|
|
333
349
|
*/
|
|
334
350
|
export async function askCorpus(
|
|
335
351
|
request: AskRequest,
|
|
336
|
-
deps: { corpus: CorpusApi; llm: CorpusLlm },
|
|
352
|
+
deps: { corpus: CorpusApi; llm: CorpusLlm; commitments?: Pick<CommitmentApi, 'listCommitments'> },
|
|
337
353
|
options: AskCorpusOptions = {},
|
|
338
354
|
): Promise<AskResult> {
|
|
339
|
-
const { candidateLimit, contextLimit, maxCharsPerDocument } = { ...DEFAULTS, ...options };
|
|
355
|
+
const { candidateLimit, contextLimit, maxCharsPerDocument, itemLimit } = { ...DEFAULTS, ...options };
|
|
340
356
|
const { corpus, llm } = deps;
|
|
341
357
|
|
|
342
358
|
// An empty scope grants nothing (see `isInScope`). Refusing here rather than
|
|
@@ -351,15 +367,40 @@ export async function askCorpus(
|
|
|
351
367
|
request,
|
|
352
368
|
candidateLimit,
|
|
353
369
|
);
|
|
354
|
-
const { retrieved, droppedOutOfScope } = retrieveForQuestion(
|
|
370
|
+
const { retrieved: documents, droppedOutOfScope } = retrieveForQuestion(
|
|
355
371
|
candidates,
|
|
356
372
|
request.question,
|
|
357
373
|
request.scope,
|
|
358
374
|
{ limit: contextLimit, now: options.now },
|
|
359
375
|
);
|
|
376
|
+
// TRACKED ITEMS. Selected by dates and states in code, in their own budget so
|
|
377
|
+
// documents can never crowd them out; they lead the prompt.
|
|
378
|
+
const items = request.mode === 'ask'
|
|
379
|
+
? await retrieveItems(
|
|
380
|
+
request.question,
|
|
381
|
+
deps.commitments,
|
|
382
|
+
request.scope,
|
|
383
|
+
{ now: options.now ?? Date.now(), timeZone: options.timeZone, ownerSub: options.ownerSub, focusNames: options.focusNames },
|
|
384
|
+
itemLimit,
|
|
385
|
+
)
|
|
386
|
+
: { intent: null, retrieved: [], matched: 0 };
|
|
387
|
+
const retrieved = [...items.retrieved, ...documents];
|
|
360
388
|
|
|
361
389
|
const freshness = await corpus.listSources().catch(() => [] as SourceFreshness[]);
|
|
362
390
|
|
|
391
|
+
if (retrieved.length === 0 && items.intent && deps.commitments) {
|
|
392
|
+
return {
|
|
393
|
+
status: 'no_evidence',
|
|
394
|
+
answer: `No tracked items match${items.intent.windowLabel ? ` ${items.intent.windowLabel}` : ''}, and no documents do either.`,
|
|
395
|
+
citations: [],
|
|
396
|
+
considered: [],
|
|
397
|
+
unresolvedCitations: [],
|
|
398
|
+
droppedOutOfScope,
|
|
399
|
+
provider: llm.describe(),
|
|
400
|
+
freshness,
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
|
|
363
404
|
if (retrieved.length === 0) {
|
|
364
405
|
// An unfiltered pull already tells us the size, so the extra read only
|
|
365
406
|
// happens on the path that is about to make a claim about the corpus.
|
|
@@ -379,7 +420,9 @@ export async function askCorpus(
|
|
|
379
420
|
const withheldFields = collectWithheld(retrieved);
|
|
380
421
|
|
|
381
422
|
const draft = await llm.answer(
|
|
382
|
-
buildAnswerRequest(request, retrieved, maxCharsPerDocument
|
|
423
|
+
buildAnswerRequest(request, retrieved, maxCharsPerDocument, items.intent
|
|
424
|
+
? { today: items.intent.today, itemWindow: items.intent.windowLabel }
|
|
425
|
+
: {}),
|
|
383
426
|
);
|
|
384
427
|
const { citations, unresolved } = resolveCitations(draft, retrieved);
|
|
385
428
|
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE WEEKLY SUMMARY ROUTE'S LOGIC (bd startsim-tmrvi), the weekly twin of
|
|
3
|
+
* `generateBriefing`: load -> compose -> script -> speak -> keep, one row per
|
|
4
|
+
* (owner, local day), a repeat tap costs nothing, text always returned, speech
|
|
5
|
+
* best-effort. SAME deps, SAME store, SAME audio path; only the composer and the
|
|
6
|
+
* wording differ. The row is the OWNER'S: there is no delivery beyond the app.
|
|
7
|
+
*/
|
|
8
|
+
import { hashString } from './cache-key';
|
|
9
|
+
import { composeWeekly, weeklyScript } from './weekly';
|
|
10
|
+
import { createEntityBriefingStore, type BriefingRecord } from './store';
|
|
11
|
+
import type { BriefingDeps, BriefingRequest } from './generate';
|
|
12
|
+
import type { WeeklySummary } from './weekly';
|
|
13
|
+
|
|
14
|
+
export const WEEKLY_SCRIPT_VERSION = 1;
|
|
15
|
+
export const weeklyExternalId = (ownerSub: string, localDate: string) => `weekly:${localDate}:${ownerSub}`;
|
|
16
|
+
|
|
17
|
+
export interface WeeklyResult {
|
|
18
|
+
summaryId: string;
|
|
19
|
+
text: string;
|
|
20
|
+
audioUrl: string | null;
|
|
21
|
+
audioReason?: string;
|
|
22
|
+
counts: WeeklySummary['counts'];
|
|
23
|
+
window: WeeklySummary['window'];
|
|
24
|
+
cached: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const reasonOf = (error: unknown) => (error instanceof Error ? error.message : String(error)).slice(0, 300);
|
|
28
|
+
|
|
29
|
+
export async function generateWeekly(deps: BriefingDeps, request: BriefingRequest = {}): Promise<WeeklyResult> {
|
|
30
|
+
const now = (deps.now ?? Date.now)();
|
|
31
|
+
const timeZone = request.timeZone ?? deps.timeZone ?? 'UTC';
|
|
32
|
+
const ttl = Math.min(deps.audioTtlSeconds ?? 300, 600);
|
|
33
|
+
const store = deps.store ?? createEntityBriefingStore(deps.http, deps.ownerSub);
|
|
34
|
+
|
|
35
|
+
const summary = composeWeekly(await deps.loadItems(), { ownerSub: deps.ownerSub, now, timeZone });
|
|
36
|
+
const script = weeklyScript(summary, { now, timeZone, name: deps.name });
|
|
37
|
+
const hash = hashString(`w${WEEKLY_SCRIPT_VERSION}␞${summary.window.today}␞${script.text}`);
|
|
38
|
+
const externalId = weeklyExternalId(deps.ownerSub, summary.window.today);
|
|
39
|
+
const stored = request.force ? null : await store.find(externalId);
|
|
40
|
+
const current = stored && stored.contentHash === hash ? stored : null;
|
|
41
|
+
|
|
42
|
+
const linkFor = async (ref: string | undefined, id: string): Promise<string | null> => {
|
|
43
|
+
if (!ref) return null;
|
|
44
|
+
try { return await deps.audio.url(ref, ttl, id); } catch { return null; }
|
|
45
|
+
};
|
|
46
|
+
const result = (record: BriefingRecord, audioUrl: string | null, cached: boolean, reason?: string): WeeklyResult => ({
|
|
47
|
+
summaryId: record.id,
|
|
48
|
+
text: record.text,
|
|
49
|
+
audioUrl,
|
|
50
|
+
...(audioUrl ? {} : { audioReason: reason ?? record.audioReason ?? 'No audio was generated.' }),
|
|
51
|
+
counts: summary.counts,
|
|
52
|
+
window: summary.window,
|
|
53
|
+
cached,
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
if (current?.audioRef) {
|
|
57
|
+
const url = await linkFor(current.audioRef, current.id);
|
|
58
|
+
if (url) return result(current, url, true);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let audioRef: string | undefined;
|
|
62
|
+
let audioMime: string | undefined;
|
|
63
|
+
let audioReason: string | undefined;
|
|
64
|
+
let usage: Record<string, unknown> | undefined;
|
|
65
|
+
try {
|
|
66
|
+
const spoken = await deps.synthesize({ text: script.text });
|
|
67
|
+
audioRef = await deps.audio.put({ noteId: `weekly-${summary.window.today}-${hash}`, audio: spoken.audio, mimeType: spoken.mimeType });
|
|
68
|
+
audioMime = spoken.mimeType;
|
|
69
|
+
usage = { provider: spoken.provider, model: spoken.model, characters: spoken.usage.characters, costUsd: spoken.usage.costUsd };
|
|
70
|
+
} catch (error) {
|
|
71
|
+
audioReason = `Speech is unavailable right now: ${reasonOf(error)}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const saved = await store.save({
|
|
75
|
+
externalId,
|
|
76
|
+
localDate: summary.window.today,
|
|
77
|
+
contentHash: hash,
|
|
78
|
+
text: script.text,
|
|
79
|
+
scriptSource: 'template',
|
|
80
|
+
items: [],
|
|
81
|
+
remaining: 0,
|
|
82
|
+
context: { itemIds: [], localDate: summary.window.today, timeZone, offsets: [] },
|
|
83
|
+
...(audioRef ? { audioRef, audioMime } : {}),
|
|
84
|
+
...(audioReason ? { audioReason } : {}),
|
|
85
|
+
...(usage ? { usage } : {}),
|
|
86
|
+
createdAt: new Date(now).toISOString(),
|
|
87
|
+
});
|
|
88
|
+
return result(saved, await linkFor(audioRef, saved.id), Boolean(current), audioReason);
|
|
89
|
+
}
|
|
@@ -6,8 +6,12 @@ export { writeBriefingScript, templateScript, scriptPrompt, scriptSystemPrompt }
|
|
|
6
6
|
export type { BriefingScript, BriefingScriptLlm, BriefingScriptOptions, ScriptSegment } from './script';
|
|
7
7
|
export { speakCount, speakDate, speakable, isUnspeakable, partOfDay, wordCount } from './speak';
|
|
8
8
|
export { generateBriefing } from './generate';
|
|
9
|
+
export { composeWeekly, weeklyScript } from './weekly';
|
|
10
|
+
export type { WeeklyEntry, WeeklyKind, WeeklyOptions, WeeklyScript, WeeklyScriptOptions, WeeklySummary } from './weekly';
|
|
11
|
+
export { generateWeekly, weeklyExternalId } from './generate-weekly';
|
|
12
|
+
export type { WeeklyResult } from './generate-weekly';
|
|
9
13
|
export type { BriefingAudio, BriefingDeps, BriefingRequest, BriefingResult, BriefingSynthesize } from './generate';
|
|
10
|
-
export { briefingResponse, briefingAudioResponse } from './respond';
|
|
14
|
+
export { briefingResponse, weeklyResponse, briefingAudioResponse } from './respond';
|
|
11
15
|
export { createEntityBriefingStore, briefingExternalId, BRIEFING_SOURCE } from './store';
|
|
12
16
|
export type { BriefingContextRecord, BriefingRecord, BriefingStore } from './store';
|
|
13
17
|
export { briefingContentHash, hashString, SCRIPT_VERSION } from './cache-key';
|
|
@@ -6,9 +6,10 @@
|
|
|
6
6
|
import type { CorpusHttp } from '../client';
|
|
7
7
|
import type { TenantEntity } from '../entities';
|
|
8
8
|
import { voiceErrorResponse } from '../voice-manage';
|
|
9
|
-
import { generateBriefing, type BriefingDeps } from './generate';
|
|
9
|
+
import { generateBriefing, type BriefingDeps, type BriefingRequest } from './generate';
|
|
10
|
+
import { generateWeekly } from './generate-weekly';
|
|
10
11
|
|
|
11
|
-
|
|
12
|
+
async function respondWith(request: Request, run: (options: BriefingRequest) => Promise<unknown>): Promise<Response> {
|
|
12
13
|
let body: { force?: unknown; timeZone?: unknown } = {};
|
|
13
14
|
try {
|
|
14
15
|
const raw = await request.text();
|
|
@@ -24,12 +25,19 @@ export async function briefingResponse(request: Request, deps: BriefingDeps): Pr
|
|
|
24
25
|
}
|
|
25
26
|
}
|
|
26
27
|
try {
|
|
27
|
-
return Response.json(await
|
|
28
|
+
return Response.json(await run({ force, timeZone }));
|
|
28
29
|
} catch (error) {
|
|
29
30
|
return voiceErrorResponse(error);
|
|
30
31
|
}
|
|
31
32
|
}
|
|
32
33
|
|
|
34
|
+
export const briefingResponse = (request: Request, deps: BriefingDeps): Promise<Response> =>
|
|
35
|
+
respondWith(request, (options) => generateBriefing(deps, options));
|
|
36
|
+
|
|
37
|
+
/** The weekly summary: same request shape, same owner-only row and audio route. */
|
|
38
|
+
export const weeklyResponse = (request: Request, deps: BriefingDeps): Promise<Response> =>
|
|
39
|
+
respondWith(request, (options) => generateWeekly(deps, options));
|
|
40
|
+
|
|
33
41
|
/** The audio, to the briefing's owner only: the row is read as the caller, so another member's id is a 404. */
|
|
34
42
|
export async function briefingAudioResponse(
|
|
35
43
|
id: string,
|
|
@@ -19,6 +19,8 @@ export interface BriefingItem {
|
|
|
19
19
|
/** Linear's own state type when the item is synced (`started`, `completed`, `canceled`, ...). */
|
|
20
20
|
linearState?: string;
|
|
21
21
|
linearIdentifier?: string;
|
|
22
|
+
/** When it was finished, when known (the weekly summary counts a done item only with this). */
|
|
23
|
+
resolvedAt?: string | null;
|
|
22
24
|
}
|
|
23
25
|
|
|
24
26
|
export type BriefingKind = 'overdue' | 'in_progress' | 'due_today';
|