@startsimpli/integrations 0.2.200 → 0.2.201
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +6 -6
- package/src/__tests__/briefing-actions.test.ts +11 -0
- package/src/__tests__/briefing-edits.test.ts +98 -0
- package/src/__tests__/converse-brain.test.ts +64 -1
- package/src/__tests__/converse-handoff.test.ts +8 -0
- package/src/__tests__/converse-meeting-brief.test.ts +72 -8
- package/src/__tests__/converse-meeting-duplex.test.ts +132 -0
- package/src/__tests__/converse-meeting-keep-speech.test.ts +87 -0
- package/src/__tests__/converse-meeting-vad.test.ts +1 -1
- package/src/__tests__/converse-spoken-form.test.ts +10 -0
- package/src/__tests__/converse-spoken-summary.test.ts +27 -6
- package/src/__tests__/converse.test.ts +29 -2
- package/src/__tests__/corpus-ask.test.ts +22 -0
- package/src/__tests__/corpus-tracker.test.tsx +12 -0
- package/src/__tests__/extract-classify.test.ts +17 -0
- package/src/__tests__/fleet-page.test.tsx +57 -0
- package/src/__tests__/fleet-view.test.ts +149 -0
- package/src/__tests__/project-basis-entity.test.ts +19 -0
- package/src/__tests__/project-basis.test.ts +21 -0
- package/src/__tests__/relay-cli.test.ts +10 -1
- package/src/__tests__/task-detail-project-guess.test.tsx +46 -0
- package/src/components/index.ts +2 -0
- package/src/components/pages/FleetPage.tsx +115 -0
- package/src/components/pages/TaskDetailPage.tsx +27 -1
- package/src/components/pages/TrackerPage.tsx +1 -1
- package/src/components/pages/task-tracker/ProjectGuess.tsx +42 -0
- package/src/corpus/ask-items.ts +7 -4
- package/src/corpus/ask.ts +1 -1
- package/src/corpus/briefing/actions/confirm.ts +9 -1
- package/src/corpus/briefing/actions/execute.ts +71 -11
- package/src/corpus/briefing/actions/log.ts +1 -1
- package/src/corpus/briefing/actions/seam.ts +18 -2
- package/src/corpus/briefing/actions/types.ts +14 -0
- package/src/corpus/briefing/intent/describe.ts +5 -1
- package/src/corpus/briefing/intent/edits.ts +92 -0
- package/src/corpus/briefing/intent/grammar.ts +3 -0
- package/src/corpus/briefing/intent/ground.ts +5 -1
- package/src/corpus/briefing/intent/match.ts +3 -1
- package/src/corpus/briefing/intent/model.ts +36 -3
- package/src/corpus/briefing/intent/resolve.ts +12 -1
- package/src/corpus/briefing/intent/types.ts +8 -0
- package/src/corpus/briefing/speak.ts +13 -0
- package/src/corpus/client.ts +2 -0
- package/src/corpus/converse/brain.ts +41 -13
- package/src/corpus/converse/briefing-queue.ts +105 -27
- package/src/corpus/converse/client.ts +6 -0
- package/src/corpus/converse/fleet-view.ts +126 -0
- package/src/corpus/converse/fleet.ts +18 -5
- package/src/corpus/converse/followups.ts +12 -2
- package/src/corpus/converse/handle.ts +21 -12
- package/src/corpus/converse/handoff.ts +7 -2
- package/src/corpus/converse/index.ts +5 -3
- package/src/corpus/converse/meeting-config.ts +8 -4
- package/src/corpus/converse/meeting.ts +66 -11
- package/src/corpus/converse/respond.ts +14 -2
- package/src/corpus/converse/spoken-form.ts +9 -2
- package/src/corpus/converse/spoken-summary.ts +30 -8
- package/src/corpus/converse/store.ts +2 -0
- package/src/corpus/converse/types.ts +14 -1
- package/src/corpus/entities.ts +2 -0
- package/src/corpus/extract.ts +9 -4
- package/src/corpus/project-basis.ts +23 -0
- package/src/corpus/types.ts +6 -0
- package/src/native/app/converseServices.ts +5 -3
- package/src/native/app/device.ts +2 -0
- package/src/native/converse/ConverseScreen.tsx +28 -0
- package/src/native/converse/__tests__/liveScreen.test.tsx +35 -2
- package/src/native/converse/__tests__/meetingIO.test.ts +55 -1
- package/src/native/converse/format.ts +2 -2
- package/src/native/converse/io.ts +15 -5
|
@@ -11,7 +11,7 @@ import { isIsoDate, parseWhen, spokenWhen, weekdayName } from './dates';
|
|
|
11
11
|
import { PRIORITY_NAMES } from './describe';
|
|
12
12
|
import type { IntentContext, IntentItem, VoiceAction } from './types';
|
|
13
13
|
|
|
14
|
-
export const MAX_ACTIONS =
|
|
14
|
+
export const MAX_ACTIONS = 8;
|
|
15
15
|
const MAX_OPEN_SHOWN = 40;
|
|
16
16
|
|
|
17
17
|
export function intentSystemPrompt(): string {
|
|
@@ -23,7 +23,11 @@ export function intentSystemPrompt(): string {
|
|
|
23
23
|
'{"type":"done","item_id":ID} {"type":"drop","item_id":ID}',
|
|
24
24
|
'{"type":"set_priority","item_id":ID,"priority":0..4} 0 critical, 1 urgent or high, 2 medium, 3 low, 4 lowest',
|
|
25
25
|
'{"type":"add_item","title":"Imperative short title","due":null | "YYYY-MM-DD"} a NEW item the person asked to add',
|
|
26
|
-
'{"type":"
|
|
26
|
+
'{"type":"rename","item_id":ID,"title":"the new title"} change an item\'s title',
|
|
27
|
+
'{"type":"add_detail","item_id":ID,"detail":"the note, in the person\'s words"} add a note to an existing item (not a new item)',
|
|
28
|
+
'{"type":"set_estimate","item_id":ID,"minutes":number} how long it will take, in minutes (an hour is 60)',
|
|
29
|
+
'{"type":"set_project","item_id":ID,"project":"project name as said"} file an existing item under a project',
|
|
30
|
+
'{"type":"undo"} undo the last change (all of the last reply\'s changes)',
|
|
27
31
|
'{"type":"clarify","question":"one short spoken question"} when you cannot tell which item or when',
|
|
28
32
|
'RULES',
|
|
29
33
|
'- Acting on the wrong item is far worse than asking. When unsure, return a single clarify and nothing else.',
|
|
@@ -35,6 +39,9 @@ export function intentSystemPrompt(): string {
|
|
|
35
39
|
'- Match descriptions loosely against titles ("the bench one", "the lease call").',
|
|
36
40
|
'- Adding something new ("add X", "remind me to X", "I need to X by Friday") is add_item with the thing as an imperative title and the date as due. Do not add anything that already exists as an item.',
|
|
37
41
|
'- The title is the WORK itself, never the act of adding it. "add a to-do for the relay to keep the status current" is the title "Keep the status current" (say who it is for only when it matters); "remind me to call the bank" is "Call the bank". Never start a title with add, create, remind me, a to-do or a task. Keep every detail the person gave, in full: do not shorten it.',
|
|
42
|
+
'- "all of those", "both", "every one" mean EVERY item in the spoken list: one action per item.',
|
|
43
|
+
'- "add a note to X" is add_detail on the existing item X, never add_item. A new title or note is kept exactly as said, in full.',
|
|
44
|
+
'- "take it out of its project", "remove it from the X project", "unfile it" is set_project with "project": null, never the named project.',
|
|
38
45
|
'- Several instructions in one reply are several actions in the order spoken.',
|
|
39
46
|
'- Anything that is not an instruction about to-dos (greetings, chatter, questions): one clarify asking them to say it again.',
|
|
40
47
|
'- Dates: resolve against today in the person\'s zone. A bare weekday is the next such day after today; "next week" is Monday of next week; "next Friday" is Friday of next week. Never return a date before today.',
|
|
@@ -89,7 +96,7 @@ export function checkModelReply(reply: string, ctx: IntentContext): Checked {
|
|
|
89
96
|
if (!raw || typeof raw !== 'object') return { ok: false, reason: 'action is not an object' };
|
|
90
97
|
const type = raw.type;
|
|
91
98
|
const id = typeof raw.item_id === 'string' ? raw.item_id : '';
|
|
92
|
-
const needsItem = ['defer', 'pull_today', 'done', 'drop', 'set_priority'].includes(String(type));
|
|
99
|
+
const needsItem = ['defer', 'pull_today', 'done', 'drop', 'set_priority', 'rename', 'add_detail', 'set_estimate', 'set_project'].includes(String(type));
|
|
93
100
|
if (needsItem && !known.has(id)) return { ok: false, reason: `unknown item ${JSON.stringify(raw.item_id)}` };
|
|
94
101
|
switch (type) {
|
|
95
102
|
case 'defer': {
|
|
@@ -123,6 +130,32 @@ export function checkModelReply(reply: string, ctx: IntentContext): Checked {
|
|
|
123
130
|
out.push({ type: 'add_item', title: t[0].toUpperCase() + t.slice(1), dueDate: due });
|
|
124
131
|
break;
|
|
125
132
|
}
|
|
133
|
+
case 'rename': {
|
|
134
|
+
const t = typeof raw.title === 'string' ? raw.title.trim() : '';
|
|
135
|
+
if (!t || t.length > 200) return { ok: false, reason: 'bad title' };
|
|
136
|
+
out.push({ type: 'rename', itemId: id, title: t[0].toUpperCase() + t.slice(1) });
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
case 'add_detail': {
|
|
140
|
+
const d = typeof raw.detail === 'string' ? raw.detail.trim() : '';
|
|
141
|
+
if (!d || d.length > 2000) return { ok: false, reason: 'bad detail' };
|
|
142
|
+
out.push({ type: 'add_detail', itemId: id, detail: d[0].toUpperCase() + d.slice(1) });
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
case 'set_estimate': {
|
|
146
|
+
const m = raw.minutes;
|
|
147
|
+
if (m === null) { out.push({ type: 'set_estimate', itemId: id, minutes: null }); break; }
|
|
148
|
+
if (typeof m !== 'number' || !Number.isFinite(m) || m <= 0 || m > 60 * 24 * 30) return { ok: false, reason: 'bad estimate' };
|
|
149
|
+
out.push({ type: 'set_estimate', itemId: id, minutes: Math.round(m) });
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
case 'set_project': {
|
|
153
|
+
if (raw.project === null) { out.push({ type: 'set_project', itemId: id, project: null }); break; }
|
|
154
|
+
const p = typeof raw.project === 'string' ? raw.project.trim() : '';
|
|
155
|
+
if (!p || p.length > 100) return { ok: false, reason: 'bad project' };
|
|
156
|
+
out.push({ type: 'set_project', itemId: id, project: p });
|
|
157
|
+
break;
|
|
158
|
+
}
|
|
126
159
|
case 'undo': out.push({ type: 'undo' }); break;
|
|
127
160
|
case 'clarify': {
|
|
128
161
|
const q = typeof raw.question === 'string' ? raw.question.trim() : '';
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* contradicts the data. A low-confidence model answer asks instead of acting.
|
|
7
7
|
* NEVER executes anything.
|
|
8
8
|
*/
|
|
9
|
+
import { matchItems } from './match';
|
|
9
10
|
import { describeActions } from './describe';
|
|
10
11
|
import { parseWithGrammar } from './grammar';
|
|
11
12
|
import { ungrounded } from './ground';
|
|
@@ -21,10 +22,20 @@ function byGrammar(ctx: IntentContext, notes: string[]): IntentResult {
|
|
|
21
22
|
return { ...out, confidence: out.actions.some((a) => a.type !== 'clarify' && a.type !== 'none') ? 1 : 0, notes };
|
|
22
23
|
}
|
|
23
24
|
|
|
25
|
+
/**
|
|
26
|
+
* The words that answer "which one?": when they name exactly one open item, the earlier instruction is read again against that item
|
|
27
|
+
* alone, so "the dad one" settles "move the bench one to Friday". Otherwise both are read together.
|
|
28
|
+
*/
|
|
29
|
+
function withAnswer(asked: IntentContext, thread: { utterance: string; question: string }): IntentContext {
|
|
30
|
+
const found = matchItems(asked.utterance, [...asked.briefed, ...asked.open.filter((o) => !asked.briefed.some((b) => b.id === o.id))]);
|
|
31
|
+
if (found.kind === 'one') return { ...asked, utterance: thread.utterance, briefed: [found.item], open: [found.item], thread: undefined };
|
|
32
|
+
return { ...asked, utterance: `${thread.utterance} ${asked.utterance}` };
|
|
33
|
+
}
|
|
34
|
+
|
|
24
35
|
export async function resolveVoiceIntent(asked: IntentContext, options: IntentOptions = {}): Promise<IntentResult> {
|
|
25
36
|
const notes: string[] = [];
|
|
26
37
|
// An answer to our question is read WITH what was said first: dates and items come from either.
|
|
27
|
-
const ctx: IntentContext = asked.thread ?
|
|
38
|
+
const ctx: IntentContext = asked.thread ? withAnswer(asked, asked.thread) : asked;
|
|
28
39
|
if (!asked.utterance.trim()) return byGrammar(ctx, ['empty utterance']);
|
|
29
40
|
|
|
30
41
|
if (options.llm) {
|
|
@@ -42,6 +42,14 @@ export type VoiceAction =
|
|
|
42
42
|
/** 0 critical, 1 urgent, 2 medium, 3 low, 4 lowest. */
|
|
43
43
|
| { type: 'set_priority'; itemId: string; priority: number }
|
|
44
44
|
| { type: 'add_item'; title: string; dueDate: string | null }
|
|
45
|
+
/** Change an item's title. */
|
|
46
|
+
| { type: 'rename'; itemId: string; title: string }
|
|
47
|
+
/** Add a note to an item's detail (appended; what was there stays). */
|
|
48
|
+
| { type: 'add_detail'; itemId: string; detail: string }
|
|
49
|
+
/** How long it will take, in minutes; null clears it. */
|
|
50
|
+
| { type: 'set_estimate'; itemId: string; minutes: number | null }
|
|
51
|
+
/** File it under a project, by the name said; null takes it out of its project. */
|
|
52
|
+
| { type: 'set_project'; itemId: string; project: string | null }
|
|
45
53
|
| { type: 'undo' }
|
|
46
54
|
/** A short thing to say back when the reply was not clear enough to act on. */
|
|
47
55
|
| { type: 'clarify'; question: string }
|
|
@@ -79,3 +79,16 @@ export function speakDatesIn(text: string, today: string): string {
|
|
|
79
79
|
return month >= 1 && month <= 12 && Number(d) >= 1 && Number(d) <= 31 ? speakDate(m, today) : m;
|
|
80
80
|
});
|
|
81
81
|
}
|
|
82
|
+
|
|
83
|
+
/** Minutes as a person says a length of time: `an hour and a half`, `forty-five minutes`, `two hours`. */
|
|
84
|
+
export function spokenMinutes(total: number): string {
|
|
85
|
+
const n = Math.max(0, Math.round(total));
|
|
86
|
+
if (n === 30) return 'half an hour';
|
|
87
|
+
const hours = Math.floor(n / 60);
|
|
88
|
+
const rest = n % 60;
|
|
89
|
+
const h = hours === 1 ? 'an hour' : `${speakCount(hours)} hours`;
|
|
90
|
+
if (!hours) return `${speakCount(rest)} ${rest === 1 ? 'minute' : 'minutes'}`;
|
|
91
|
+
if (!rest) return h;
|
|
92
|
+
if (rest === 30) return `${h} and a half`;
|
|
93
|
+
return `${h} and ${speakCount(rest)} ${rest === 1 ? 'minute' : 'minutes'}`;
|
|
94
|
+
}
|
package/src/corpus/client.ts
CHANGED
|
@@ -1445,8 +1445,10 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
|
|
|
1445
1445
|
wire.owner_sub = patch.ownerSubs[0] ?? '';
|
|
1446
1446
|
}
|
|
1447
1447
|
if (patch.dueAt !== undefined) wire.due_at = patch.dueAt;
|
|
1448
|
+
if (patch.projectBasis !== undefined) wire.project_basis = patch.projectBasis ?? '';
|
|
1448
1449
|
if (patch.subtype !== undefined) wire.subtype = patch.subtype;
|
|
1449
1450
|
if (patch.priority !== undefined) wire.priority = patch.priority;
|
|
1451
|
+
if (patch.estimateMinutes !== undefined) wire.estimate_minutes = patch.estimateMinutes;
|
|
1450
1452
|
if (patch.resolvedAt !== undefined) wire.resolved_at = patch.resolvedAt;
|
|
1451
1453
|
// WHEN it was finished, stamped on the transition to done only (never on
|
|
1452
1454
|
// an edit to an already-done item, never over a value the caller sent):
|
|
@@ -17,14 +17,16 @@ import { speakable } from '../briefing/speak';
|
|
|
17
17
|
import type { BriefingItem } from '../briefing/types';
|
|
18
18
|
import { FLEET_FRESH_MS, ageWords } from './fleet';
|
|
19
19
|
import { routeUtterance } from './route';
|
|
20
|
-
import { spokenSummary } from './spoken-summary';
|
|
21
|
-
import { sourcesOfDocs } from './sources';
|
|
20
|
+
import { spokenRest, spokenSummary, WANTS_THE_REST } from './spoken-summary';
|
|
21
|
+
import { askSources, sourcesOfDocs } from './sources';
|
|
22
|
+
import type { SourceDocument } from '../types';
|
|
22
23
|
import { WRAP_UP } from './wrap-up';
|
|
23
24
|
import { itemAnswer } from './item-answers';
|
|
24
25
|
import { followUp, mightFollowUp, type PlayedItem } from './followups';
|
|
25
26
|
import { ACTIVITY_QUESTION, composeActivity, forOwner, type Activity, type ActivityWindow } from '../activity';
|
|
27
|
+
import { localDate } from '../today';
|
|
26
28
|
import { questionWindow } from '../ask-items-intent';
|
|
27
|
-
import { BRIEF_ME, NEEDS_ME, buildQueue, firstPrompt, relayItemsFrom, stepBriefing, type BriefingEffect, type BriefingState } from './briefing-queue';
|
|
29
|
+
import { BRIEF_ME, NEEDS_ME, buildQueue, firstPrompt, relayItemsFrom, startBriefing, stepBriefing, type BriefingEffect, type BriefingState } from './briefing-queue';
|
|
28
30
|
import type { ConverseBrain, ConverseSource, HistoryLine } from './types';
|
|
29
31
|
|
|
30
32
|
const MIN_AUTO = 0.85;
|
|
@@ -42,7 +44,7 @@ export interface ConverseBrainDeps {
|
|
|
42
44
|
/** What happened in a calendar window (to-dos finished or added, conversations, notes): "what did I do yesterday". Omit: those go to Ask. */
|
|
43
45
|
loadActivity?(window: ActivityWindow, timeZone: string): Promise<Activity>;
|
|
44
46
|
/** Answers a question over the person's items, notes and documents; the app wires `askCorpus`. */
|
|
45
|
-
ask(input: { question: string; timeZone: string; now: number }): Promise<{ answer: string; status?: string; sources?: ConverseSource[] }>;
|
|
47
|
+
ask(input: { question: string; timeZone: string; now: number }): Promise<{ answer: string; status?: string; sources?: ConverseSource[]; /** Ask's own citations: used for the sources when `sources` is not given. */ citations?: Array<{ document: SourceDocument }> }>;
|
|
46
48
|
minAutoConfidence?: number;
|
|
47
49
|
/** Sorts a line into work for the relay / a fleet-status question / other. Omit: everything not an item edit goes to Ask. */
|
|
48
50
|
routeLlm?: BriefingScriptLlm | null;
|
|
@@ -172,6 +174,15 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
|
|
|
172
174
|
const effect: BriefingEffect | undefined = step.effect;
|
|
173
175
|
let text = step.reply;
|
|
174
176
|
let did: string[] | undefined;
|
|
177
|
+
if (effect?.kind === 'skip') {
|
|
178
|
+
// Remembered for today only: a new day brings it back.
|
|
179
|
+
const today = localDate(now, timeZone);
|
|
180
|
+
const log = await deps.log.load().catch(() => null);
|
|
181
|
+
if (log) {
|
|
182
|
+
const kept = log.skips?.date === today ? log.skips.keys : [];
|
|
183
|
+
await deps.log.save({ ...log, skips: { date: today, keys: [...new Set([...kept, effect.key])].slice(-200) } }).catch(() => undefined);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
175
186
|
if (effect?.kind === 'todo') {
|
|
176
187
|
const outcome = await timed('act', () => executeVoiceActions({
|
|
177
188
|
actions: [effect.action], clientActionId: `brief-${now}-${Math.abs(hash(`${utterance}${'itemId' in effect.action ? effect.action.itemId : ''}`))}`.slice(0, 64),
|
|
@@ -183,7 +194,7 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
|
|
|
183
194
|
return { text, briefing: step.state, intent: 'briefing' as const, ...(did?.length ? { did } : {}), ...(effect?.kind === 'relay' ? { forRelay: true, relayText: effect.text } : {}) };
|
|
184
195
|
}
|
|
185
196
|
|
|
186
|
-
async function run({ utterance, history, timeZone, now, briefing, context }: Parameters<ConverseBrain>[0], timed: Timed): ReturnType<ConverseBrain> {
|
|
197
|
+
async function run({ utterance, history, timeZone, now, briefing, context, pending }: Parameters<ConverseBrain>[0], timed: Timed): ReturnType<ConverseBrain> {
|
|
187
198
|
// Lines that name the relay go first, so "add a to-do for the relay" is for the relay, not a plan item.
|
|
188
199
|
if (ADDRESSES_RELAY.test(utterance)) {
|
|
189
200
|
const routed = await viaRoute(utterance, history, now, timed);
|
|
@@ -191,11 +202,20 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
|
|
|
191
202
|
}
|
|
192
203
|
// A briefing in progress: this is the answer to the item being asked.
|
|
193
204
|
if (briefing) {
|
|
194
|
-
const step = stepBriefing(briefing, utterance);
|
|
205
|
+
const step = stepBriefing(briefing, utterance, { now, timeZone });
|
|
195
206
|
if (!step.passThrough) return applyStep(step, utterance, now, timeZone, timed);
|
|
196
207
|
}
|
|
197
208
|
// "Parse that note" / "that's it" / "I'm done": he is wrapping up. The turn files the conversation through the normal End.
|
|
198
209
|
if (WRAP_UP.test(utterance.trim())) return { text: 'Filing it now.', finish: true, intent: 'note' as const };
|
|
210
|
+
// "Yes" / "the rest" right after a shortened answer: read what was left out (itself said short, with another offer when it is long).
|
|
211
|
+
if (!pending && WANTS_THE_REST.test(utterance.trim())) {
|
|
212
|
+
const lastSaid = [...history].reverse().find((l) => l.role === 'assistant')?.text;
|
|
213
|
+
const rest = lastSaid ? spokenRest(lastSaid) : undefined;
|
|
214
|
+
if (rest) {
|
|
215
|
+
const short = spokenSummary(rest);
|
|
216
|
+
return { text: rest, intent: 'question' as const, ...(short ? { spoken: short } : {}) };
|
|
217
|
+
}
|
|
218
|
+
}
|
|
199
219
|
// A follow-up about the items the last answer listed ("move the second one to Friday", "tell me more about the first").
|
|
200
220
|
let itemRows: BriefingItem[] | null = null;
|
|
201
221
|
if (context?.items?.length && mightFollowUp(utterance)) {
|
|
@@ -233,9 +253,10 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
|
|
|
233
253
|
timed('items', () => deps.loadItems().catch(() => [] as BriefingItem[])),
|
|
234
254
|
timed('fleet', async () => deps.loadFleetStatus?.().catch(() => null) ?? null),
|
|
235
255
|
]);
|
|
236
|
-
const
|
|
237
|
-
|
|
238
|
-
const state
|
|
256
|
+
const log = await timed('log', () => deps.log.load().catch(() => null));
|
|
257
|
+
const skipped = log?.skips?.date === localDate(now, timeZone) ? log.skips.keys : [];
|
|
258
|
+
const state = startBriefing({ items: rows, relayItems: snap ? relayItemsFrom(snap.text) : [], now, timeZone, relayFirst: NEEDS_ME.test(utterance), skipped });
|
|
259
|
+
if (!state) return { text: 'Nothing needs you right now.', intent: 'briefing' as const };
|
|
239
260
|
return { text: firstPrompt(state), briefing: state, intent: 'briefing' as const };
|
|
240
261
|
}
|
|
241
262
|
// A QUESTION is almost never an item edit, and the routing model does not depend on the intent model: start it now so a
|
|
@@ -258,10 +279,16 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
|
|
|
258
279
|
]);
|
|
259
280
|
const open = openRows.map(intentItem);
|
|
260
281
|
const intent = asking ? null : await timed('intent', () => resolveVoiceIntent(
|
|
261
|
-
{ utterance, now, timeZone, briefed: [], open, readingId: null, hasUndo: Boolean(log?.stack.length) },
|
|
282
|
+
{ utterance, now, timeZone, briefed: [], open, readingId: null, hasUndo: Boolean(log?.stack.length), ...(pending ? { thread: pending } : {}) },
|
|
262
283
|
{ llm: deps.intentLlm ?? null, ...(deps.intentTimeoutMs ? { timeoutMs: deps.intentTimeoutMs } : {}) },
|
|
263
284
|
).catch(() => null));
|
|
264
285
|
|
|
286
|
+
// A which-one question about an instruction is asked out loud and kept, so the next words answer it ("the dad one").
|
|
287
|
+
const clarify = intent?.actions.length === 1 && intent.actions[0].type === 'clarify' ? intent.actions[0].question : null;
|
|
288
|
+
if (clarify && !pending && /\bwhich\b/i.test(clarify) && EXPLICIT_TODO.test(utterance.trim())) {
|
|
289
|
+
return { text: clarify, intent: 'command' as const, pending: { utterance, question: clarify } };
|
|
290
|
+
}
|
|
291
|
+
|
|
265
292
|
const real = intent?.actions.filter((a) => a.type !== 'clarify' && a.type !== 'none') ?? [];
|
|
266
293
|
const sure = intent && real.length === intent.actions.length && real.length > 0 && (intent.confidence ?? 1) >= (deps.minAutoConfidence ?? MIN_AUTO);
|
|
267
294
|
if (intent && sure) {
|
|
@@ -269,7 +296,7 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
|
|
|
269
296
|
actions: intent.actions, clientActionId: `converse-${now}-${Math.abs(hash(utterance))}`.slice(0, 64), seam: deps.seam, log: deps.log,
|
|
270
297
|
ownerSub: deps.ownerSub, now: () => now, timeZone,
|
|
271
298
|
}));
|
|
272
|
-
return { text: outcome.text, did: outcome.results.map((r) => r.spoken).filter(Boolean), intent: 'command' as const };
|
|
299
|
+
return { text: outcome.text, did: outcome.results.map((r) => r.spoken).filter(Boolean), intent: 'command' as const, pending: null };
|
|
273
300
|
}
|
|
274
301
|
|
|
275
302
|
if (!ADDRESSES_RELAY.test(utterance)) {
|
|
@@ -282,8 +309,9 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
|
|
|
282
309
|
const full = speakable(answered.answer ?? '', 400) || (answered.answer ?? '').trim();
|
|
283
310
|
if (!full || GIVE_UP.test(full)) return { text: CANNOT_SEE, intent: 'question' as const };
|
|
284
311
|
const short = spokenSummary(full);
|
|
285
|
-
const
|
|
286
|
-
|
|
312
|
+
const sources = answered.sources ?? (answered.citations ? askSources(answered) : undefined);
|
|
313
|
+
const listed: PlayedItem[] = (sources ?? []).filter((x) => x.id.startsWith('item:')).map((x) => ({ id: x.id.replace(/^item:/, ''), title: x.title }));
|
|
314
|
+
return { text: full, intent: 'question' as const, ...(short ? { spoken: short } : {}), ...(sources?.length ? { sources } : {}), ...(listed.length ? { context: { items: listed } } : {}) };
|
|
287
315
|
}
|
|
288
316
|
|
|
289
317
|
return async (input) => {
|
|
@@ -12,9 +12,10 @@
|
|
|
12
12
|
* assistant and the briefing stays open where it was.
|
|
13
13
|
*/
|
|
14
14
|
import type { BriefingItem } from '../briefing/types';
|
|
15
|
-
import { speakable } from '../briefing/speak';
|
|
16
|
-
import { spokenWhen } from '../briefing/intent/dates';
|
|
15
|
+
import { speakCount, speakable } from '../briefing/speak';
|
|
16
|
+
import { normalizeSpeech, spokenWhen, splitWhen } from '../briefing/intent/dates';
|
|
17
17
|
import type { VoiceAction } from '../briefing/intent/types';
|
|
18
|
+
import { contentWords } from '../briefing/intent/match';
|
|
18
19
|
import { dueDay, localDate } from '../today';
|
|
19
20
|
|
|
20
21
|
export interface QueueItem {
|
|
@@ -32,11 +33,23 @@ export interface QueueItem {
|
|
|
32
33
|
/** To-dos only: why it is in the queue. */
|
|
33
34
|
when?: 'overdue' | 'today';
|
|
34
35
|
}
|
|
35
|
-
export interface BriefingState {
|
|
36
|
+
export interface BriefingState {
|
|
37
|
+
queue: QueueItem[];
|
|
38
|
+
index: number;
|
|
39
|
+
/** Old overdue items left out of the walk (said once at the end, never read one by one). */
|
|
40
|
+
older?: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** What an item with no project is called out loud. */
|
|
44
|
+
export const UNFILED = 'Unfiled';
|
|
45
|
+
/** The key a skip is remembered under for the day: the to-do's id, or the relay question's own words. */
|
|
46
|
+
export const skipKey = (q: QueueItem): string => (q.kind === 'todo' ? q.itemId ?? q.id : `relay:${q.project}:${q.text}`);
|
|
36
47
|
|
|
37
48
|
/** What the walk wants done after an answer. The caller does it (it owns the item seam and the relay inbox). */
|
|
38
49
|
export type BriefingEffect =
|
|
39
50
|
| { kind: 'todo'; action: VoiceAction }
|
|
51
|
+
/** Skipped: remember it for the rest of today so the next briefing does not bring it back. */
|
|
52
|
+
| { kind: 'skip'; key: string }
|
|
40
53
|
| { kind: 'relay'; text: string };
|
|
41
54
|
|
|
42
55
|
export interface BriefingStep {
|
|
@@ -64,6 +77,8 @@ export const BRIEF_ME = new RegExp(
|
|
|
64
77
|
const norm = (s: string) => s.toLowerCase().replace(/[’]/g, "'").replace(/[^a-z0-9' ]+/g, ' ').replace(/\s+/g, ' ').trim();
|
|
65
78
|
const cap = (s: string) => (s ? s[0].toUpperCase() + s.slice(1) : s);
|
|
66
79
|
const MAX_TODOS = 8;
|
|
80
|
+
/** Overdue items that are not urgent: how many are read out; the rest are a count. */
|
|
81
|
+
const MAX_OLD_OVERDUE = 3;
|
|
67
82
|
const MAX_RELAY = 12;
|
|
68
83
|
|
|
69
84
|
/** What the relay is waiting on him for, read from its snapshot: bullets under a "waiting on you / open questions" heading. */
|
|
@@ -94,28 +109,68 @@ export function relayItemsFrom(snapshot: string): Array<Pick<QueueItem, 'project
|
|
|
94
109
|
/** "What needs me / what do you need from me" is about what is waiting on HIM: the relay's questions come first, his own due items after. */
|
|
95
110
|
export const NEEDS_ME = /\b(needs? (me|my attention|a yes|a decision|an answer)|need from me)\b/i;
|
|
96
111
|
|
|
97
|
-
export
|
|
112
|
+
export interface QueueInput {
|
|
113
|
+
items: BriefingItem[];
|
|
114
|
+
relayItems: Array<Pick<QueueItem, 'project' | 'text' | 'more'>>;
|
|
115
|
+
now: number;
|
|
116
|
+
timeZone: string;
|
|
117
|
+
relayFirst?: boolean;
|
|
118
|
+
/** Keys (see `skipKey`) skipped earlier today: left out. */
|
|
119
|
+
skipped?: string[];
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Most important first: urgent, then what is due today, then by priority, then the most recently overdue (not the oldest). */
|
|
123
|
+
function rank(a: { i: BriefingItem; day: string }, b: { i: BriefingItem; day: string }, today: string): number {
|
|
124
|
+
const urgent = (x: BriefingItem) => ((x.priority ?? 9) <= 1 ? 0 : 1);
|
|
125
|
+
const isToday = (d: string) => (d === today ? 0 : 1);
|
|
126
|
+
return urgent(a.i) - urgent(b.i) || isToday(a.day) - isToday(b.day) || (a.i.priority ?? 9) - (b.i.priority ?? 9) || (a.day < b.day ? 1 : a.day > b.day ? -1 : 0);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function rankQueue(input: QueueInput): { queue: QueueItem[]; older: number } {
|
|
98
130
|
const today = localDate(input.now, input.timeZone);
|
|
131
|
+
const skipped = new Set(input.skipped ?? []);
|
|
99
132
|
const open = (i: BriefingItem) => !['done', 'dropped'].includes(i.status) && !['completed', 'canceled'].includes(i.linearState ?? '');
|
|
100
|
-
const
|
|
133
|
+
const ranked = input.items
|
|
101
134
|
.filter(open)
|
|
135
|
+
.filter((i) => !skipped.has(i.id))
|
|
102
136
|
.map((i) => ({ i, day: dueDay(i.dueAt, input.timeZone) }))
|
|
103
137
|
.filter((x): x is { i: BriefingItem; day: string } => x.day !== null && x.day <= today)
|
|
104
|
-
.sort((a, b) => (a
|
|
105
|
-
|
|
138
|
+
.sort((a, b) => rank(a, b, today));
|
|
139
|
+
const due: typeof ranked = [];
|
|
140
|
+
let older = 0;
|
|
141
|
+
let oldRead = 0;
|
|
142
|
+
for (const x of ranked) {
|
|
143
|
+
const old = x.day < today && (x.i.priority ?? 9) > 1;
|
|
144
|
+
if (old && oldRead >= MAX_OLD_OVERDUE) { older += 1; continue; }
|
|
145
|
+
if (due.length >= MAX_TODOS) { if (old) older += 1; continue; }
|
|
146
|
+
if (old) oldRead += 1;
|
|
147
|
+
due.push(x);
|
|
148
|
+
}
|
|
106
149
|
const todos: QueueItem[] = due.map(({ i, day }) => {
|
|
107
150
|
const overdue = day < today;
|
|
108
|
-
const title = cap(speakable(i.title,
|
|
151
|
+
const title = cap(speakable(i.title, 12)) || 'That item';
|
|
109
152
|
const dueWords = overdue ? `overdue since ${spokenWhen(day, today)}` : 'due today';
|
|
110
|
-
return { id: `todo:${i.id}`, kind: 'todo', project: i.focusName?.trim() ||
|
|
153
|
+
return { id: `todo:${i.id}`, kind: 'todo', project: i.focusName?.trim() || UNFILED, text: title, question: 'Do it today?', more: `${title}, ${dueWords}.`, itemId: i.id, when: overdue ? 'overdue' : 'today' };
|
|
111
154
|
});
|
|
112
|
-
const relay: QueueItem[] = input.relayItems
|
|
155
|
+
const relay: QueueItem[] = input.relayItems
|
|
156
|
+
.map((r, n): QueueItem => ({ id: `relay:${n}`, kind: 'relay', project: r.project, text: r.text, question: 'Yes or no?', more: r.more }))
|
|
157
|
+
.filter((q) => !skipped.has(skipKey(q)));
|
|
113
158
|
// BY PROJECT: projects in the order they first appear (his own due items first), each with its to-dos then the relay's questions.
|
|
114
159
|
const order: string[] = [];
|
|
115
160
|
const lead = input.relayFirst ? relay : todos;
|
|
116
161
|
const rest = input.relayFirst ? todos : relay;
|
|
117
162
|
for (const q of [...lead, ...rest]) if (!order.includes(q.project)) order.push(q.project);
|
|
118
|
-
return order.flatMap((p) => [...lead.filter((t) => t.project === p), ...rest.filter((r) => r.project === p)]);
|
|
163
|
+
return { queue: order.flatMap((p) => [...lead.filter((t) => t.project === p), ...rest.filter((r) => r.project === p)]), older };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function buildQueue(input: QueueInput): QueueItem[] {
|
|
167
|
+
return rankQueue(input).queue;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** A fresh walk, or null when nothing needs him. */
|
|
171
|
+
export function startBriefing(input: QueueInput): BriefingState | null {
|
|
172
|
+
const { queue, older } = rankQueue(input);
|
|
173
|
+
return queue.length ? { queue, index: 0, ...(older ? { older } : {}) } : null;
|
|
119
174
|
}
|
|
120
175
|
|
|
121
176
|
const sentence = (q: QueueItem) => `${q.text}${q.kind === 'todo' ? (q.when === 'overdue' ? ', overdue' : ', due today') : ''}`;
|
|
@@ -138,10 +193,24 @@ const SKIP = /^(skip( it)?|next( one)?|pass|move on|leave it)$/;
|
|
|
138
193
|
const DONE = /^(done|finished|already (done|did it)|it'?s done|completed?)\b/;
|
|
139
194
|
const DROP = /^(drop( it)?|delete it|cancel it|forget it|remove it)$/;
|
|
140
195
|
const YES = /^(yes|yeah|yep|yup|sure|ok|okay|do it|go ahead|go|approved?|please do|today|do it today)\b/;
|
|
141
|
-
const NO = /^(no|nope|nah|not today|not now|later|not yet
|
|
196
|
+
const NO = /^(no|nope|nah|not today|not now|later|not yet)\b/;
|
|
197
|
+
/** "later today", "this afternoon", "tonight", "in a bit": not now, but today: it comes back at the end of this walk, with no change. */
|
|
198
|
+
const LATER_TODAY = /^(?:(?:ask me |remind me |come back |circle back )?(?:to it |about it )?(?:later today|later this (?:afternoon|evening)|this (?:afternoon|evening)|tonight|in a bit|in a while|after lunch|later on today)|ask me (?:again )?later)$/;
|
|
199
|
+
|
|
200
|
+
export interface StepContext { now: number; timeZone: string }
|
|
201
|
+
|
|
202
|
+
/** A date answer ("tomorrow", "next week", "Monday"): a short reply that is only a date. */
|
|
203
|
+
function dateAnswer(said: string, ctx: StepContext | undefined) {
|
|
204
|
+
if (!ctx) return null;
|
|
205
|
+
const split = splitWhen(said, ctx.now, ctx.timeZone);
|
|
206
|
+
if (!split || split.when.later || !split.when.date) return null;
|
|
207
|
+
const left = contentWords(split.rest.replace(/\b(?:move|push|put|do|it|that|this|to|until|till|on|for|by|please|can|you|make|set|snooze|remind|me|ask|about)\b/g, ' '));
|
|
208
|
+
return left.length ? null : split.when;
|
|
209
|
+
}
|
|
142
210
|
|
|
143
|
-
export function stepBriefing(state: BriefingState, utterance: string): BriefingStep {
|
|
144
|
-
|
|
211
|
+
export function stepBriefing(state: BriefingState, utterance: string, ctx?: StepContext): BriefingStep {
|
|
212
|
+
let { queue } = state;
|
|
213
|
+
const { index } = state;
|
|
145
214
|
const q = queue[index];
|
|
146
215
|
if (!q) return { reply: 'That is everything.', state: null };
|
|
147
216
|
const said = norm(utterance);
|
|
@@ -151,19 +220,28 @@ export function stepBriefing(state: BriefingState, utterance: string): BriefingS
|
|
|
151
220
|
if (MORE.test(said)) return { reply: `${q.more} ${q.question}`, state };
|
|
152
221
|
|
|
153
222
|
let effect: BriefingEffect | undefined;
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
}
|
|
163
|
-
|
|
223
|
+
let backAtEnd = false;
|
|
224
|
+
const date = q.kind === 'todo' ? dateAnswer(said, ctx) : null;
|
|
225
|
+
if (SKIP.test(said)) effect = { kind: 'skip', key: skipKey(q) };
|
|
226
|
+
else if (q.kind === 'relay') {
|
|
227
|
+
effect = { kind: 'relay', text: `Answer on "${q.text}" (${q.project}): ${utterance.trim()}` };
|
|
228
|
+
} else if (LATER_TODAY.test(said)) backAtEnd = !q.id.endsWith(':again');
|
|
229
|
+
else if (DROP.test(said)) effect = { kind: 'todo', action: { type: 'drop', itemId: q.itemId! } };
|
|
230
|
+
else if (DONE.test(said)) effect = { kind: 'todo', action: { type: 'done', itemId: q.itemId! } };
|
|
231
|
+
else if (date && date.date === localDate(ctx!.now, ctx!.timeZone)) effect = { kind: 'todo', action: { type: 'pull_today', itemId: q.itemId!, label: 'today' } };
|
|
232
|
+
else if (date) effect = { kind: 'todo', action: { type: 'defer', itemId: q.itemId!, to: date.date as string, label: date.label } };
|
|
233
|
+
else if (YES.test(said)) effect = { kind: 'todo', action: { type: 'pull_today', itemId: q.itemId! } };
|
|
234
|
+
else if (NO.test(said)) effect = { kind: 'todo', action: { type: 'defer', itemId: q.itemId!, to: 'later' } };
|
|
235
|
+
else return { reply: '', state, passThrough: true };
|
|
236
|
+
|
|
237
|
+
// "Later today" changes nothing; the item is asked once more after the rest.
|
|
238
|
+
if (backAtEnd) queue = [...queue, { ...q, id: `${q.id}:again` }];
|
|
239
|
+
const noted = backAtEnd ? 'Noted, I will ask again at the end.' : 'Noted.';
|
|
164
240
|
const next = index + 1;
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
241
|
+
const tail = state.older ? ` ${speakCountOf(state.older)} older overdue ${state.older === 1 ? 'item is' : 'items are'} still open. Ask me what is overdue.` : '';
|
|
242
|
+
if (next >= queue.length) return { reply: `${noted === 'Noted.' ? 'Noted. That is everything.' : `${noted} That is everything.`}${tail}`, state: null, ...(effect ? { effect } : {}) };
|
|
243
|
+
const after: BriefingState = { ...state, queue, index: next };
|
|
244
|
+
return { reply: `${noted} ${prompt(queue, next, true)}`, state: after, ...(effect ? { effect } : {}) };
|
|
168
245
|
}
|
|
169
246
|
|
|
247
|
+
const speakCountOf = (n: number) => cap(speakCount(n));
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* (an <audio src> cannot send one). No React, no DOM beyond fetch/FormData, so the web page and the native
|
|
4
4
|
* tab call the same thing.
|
|
5
5
|
*/
|
|
6
|
+
import type { FleetView } from './fleet-view';
|
|
6
7
|
import type { ConverseEndResult, ConverseThread, ConverseTurnResult } from './types';
|
|
7
8
|
|
|
8
9
|
export class ConverseClientError extends Error {
|
|
@@ -19,6 +20,8 @@ export interface ConverseClient {
|
|
|
19
20
|
end(conversationId: string): Promise<ConverseEndResult>;
|
|
20
21
|
/** The thread from turn `after` + 1 on: how a page finds out the relay wrote into it. */
|
|
21
22
|
thread(conversationId: string, after: number): Promise<ConverseThread>;
|
|
23
|
+
/** The relay's fleet snapshot, parsed (`snapshot: null` before the relay has posted). */
|
|
24
|
+
fleet(): Promise<{ snapshot: { text: string; updatedAt: string; view: FleetView | null } | null }>;
|
|
22
25
|
/** Fetches a turn's audio and returns an object URL to play. */
|
|
23
26
|
audioUrl(path: string): Promise<string>;
|
|
24
27
|
}
|
|
@@ -53,6 +56,9 @@ export function createConverseClient(options: {
|
|
|
53
56
|
body.append('timeZone', timeZone || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC');
|
|
54
57
|
return (await (await call(base, { method: 'POST', body }, 'That turn failed')).json()) as ConverseTurnResult;
|
|
55
58
|
},
|
|
59
|
+
async fleet() {
|
|
60
|
+
return (await (await call(`${base}/fleet-status`, { method: 'GET', cache: 'no-store' }, 'Could not load the fleet')).json()) as Awaited<ReturnType<ConverseClient['fleet']>>;
|
|
61
|
+
},
|
|
56
62
|
async end(conversationId) {
|
|
57
63
|
return (await (await call(`${base}/end`, {
|
|
58
64
|
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ conversation_id: conversationId }),
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fleet as structure, not prose (Tandem /fleet). The relay posts three RAW inputs next to the text snapshot:
|
|
3
|
+
* `roles.md` (who leads what), the open-loops ledger (what waits on whom) and `bridge find ""` (who is live and what each
|
|
4
|
+
* is for). This module is the ONE parser: relay -> role leads -> the sessions each lead owns, then everyone else.
|
|
5
|
+
*/
|
|
6
|
+
export interface FleetInputs { roles?: string; loops?: string; sessions?: string; ports?: string }
|
|
7
|
+
export interface FleetSection { title: string; items: string[] }
|
|
8
|
+
export interface FleetPort { project: string; range: string; base: string; url: string | null; notes: string }
|
|
9
|
+
|
|
10
|
+
export interface FleetSession { id: string; name: string; machine: string; goal: string; repo: string; branch: string; status: 'live' | 'dormant' }
|
|
11
|
+
export interface RoleRow { role: string; sessionId: string | null; childIds: string[]; notes: string }
|
|
12
|
+
export interface FleetLead { role: string; notes: string; session: FleetSession | null; children: FleetSession[]; /** The id roles.md lists, when it is not the live one. */ listedId?: string }
|
|
13
|
+
export interface FleetView {
|
|
14
|
+
relay: FleetSession | null;
|
|
15
|
+
leads: FleetLead[];
|
|
16
|
+
others: FleetSession[];
|
|
17
|
+
waitingOnQuinn: string[];
|
|
18
|
+
waitingOnSessions: string[];
|
|
19
|
+
rolesUpdated: string | null;
|
|
20
|
+
loopsUpdated: string | null;
|
|
21
|
+
ports: FleetPort[];
|
|
22
|
+
/** The ledger's other headed sections (state notes, parked items, ...), in file order. */
|
|
23
|
+
sections: FleetSection[];
|
|
24
|
+
/** Hand-edited markdown that did not fit: shown as-is, never a failure. */
|
|
25
|
+
unparsed: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const HEX8 = /\b[0-9a-f]{8}\b/g;
|
|
29
|
+
const updatedOf = (md: string) => /^Updated\s+(.+)$/m.exec(md)?.[1].trim() ?? null;
|
|
30
|
+
|
|
31
|
+
export function parseRoles(md: string): { updated: string | null; rows: RoleRow[]; unparsed: string[] } {
|
|
32
|
+
const rows: RoleRow[] = [];
|
|
33
|
+
const unparsed: string[] = [];
|
|
34
|
+
for (const line of md.split('\n')) {
|
|
35
|
+
const t = line.trim();
|
|
36
|
+
if (t && !t.startsWith('|') && !t.startsWith('#') && !/^Updated\s/.test(t)) unparsed.push(t);
|
|
37
|
+
if (!t.startsWith('|')) continue;
|
|
38
|
+
const cells = line.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
|
|
39
|
+
if (/^[-:\s]+$/.test(cells.join('')) || cells[0].toLowerCase() === 'role') continue;
|
|
40
|
+
if (cells.length < 2 || !cells[0]) { unparsed.push(t); continue; }
|
|
41
|
+
const [role, live, notes = ''] = cells;
|
|
42
|
+
const sessionId = /^none/i.test(live) ? null : live.match(HEX8)?.[0] ?? null;
|
|
43
|
+
const childIds = [...new Set(notes.match(HEX8) ?? [])].filter((id) => id !== sessionId);
|
|
44
|
+
rows.push({ role, sessionId, childIds, notes });
|
|
45
|
+
}
|
|
46
|
+
return { updated: updatedOf(md), rows, unparsed };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function parseLoops(md: string): { updated: string | null; waitingOnQuinn: string[]; waitingOnSessions: string[]; sections: FleetSection[]; unparsed: string[] } {
|
|
50
|
+
const out = { updated: updatedOf(md), waitingOnQuinn: [] as string[], waitingOnSessions: [] as string[], sections: [] as FleetSection[], unparsed: [] as string[] };
|
|
51
|
+
let into: string[] | null = null;
|
|
52
|
+
for (const line of md.split('\n')) {
|
|
53
|
+
const h = /^#{2,}\s+(.*)$/.exec(line);
|
|
54
|
+
if (h) {
|
|
55
|
+
const title = h[1].trim();
|
|
56
|
+
if (/^waiting on quinn/i.test(title)) into = out.waitingOnQuinn;
|
|
57
|
+
else if (/^(waiting on sessions|relay owes)/i.test(title)) into = out.waitingOnSessions;
|
|
58
|
+
else { const sec = { title, items: [] as string[] }; out.sections.push(sec); into = sec.items; }
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const t = line.trim();
|
|
62
|
+
const b = /^[-*]\s+(.+)$/.exec(t);
|
|
63
|
+
if (b && into) into.push(b[1].trim());
|
|
64
|
+
else if (t && !t.startsWith('#') && !/^Updated\s/.test(t)) (into ?? out.unparsed).push(t);
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** ports.md table: | Project | Range | Base (...) | Notes |; the URL is the first 4-digit port in the Base cell. */
|
|
70
|
+
export function parsePorts(md: string): FleetPort[] {
|
|
71
|
+
const out: FleetPort[] = [];
|
|
72
|
+
for (const line of md.split('\n')) {
|
|
73
|
+
const t = line.trim();
|
|
74
|
+
if (!t.startsWith('|')) continue;
|
|
75
|
+
const cells = t.replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
|
|
76
|
+
if (cells.length < 3 || /^[-:\s]+$/.test(cells.join('')) || cells[0].toLowerCase() === 'project') continue;
|
|
77
|
+
const port = /\b(\d{4,5})\b/.exec(cells[2])?.[1];
|
|
78
|
+
out.push({ project: cells[0], range: cells[1], base: cells[2], url: port ? `http://localhost:${port}` : null, notes: cells[3] ?? '' });
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** `bridge find ""` lines: [live] `machine · name · id` goal repo@branch [model ..] */
|
|
84
|
+
export function parseBridgeFind(out: string): FleetSession[] {
|
|
85
|
+
const sessions: FleetSession[] = [];
|
|
86
|
+
for (const line of out.split('\n')) {
|
|
87
|
+
const m = /^\[(live|dormant)\]\s+`([^`]+)`\s*(.*)$/.exec(line);
|
|
88
|
+
if (!m) continue;
|
|
89
|
+
const parts = m[2].split(' · ').map((p) => p.trim());
|
|
90
|
+
const id = parts[parts.length - 1];
|
|
91
|
+
if (!/^[0-9a-f]{8}$/.test(id)) continue; // spawn runners and anything without a session id
|
|
92
|
+
const segs = m[3].split(/\s{2,}/).map((s) => s.trim()).filter(Boolean);
|
|
93
|
+
const rb = segs.find((s) => /^[^\s@]+@\S+$/.test(s)) ?? '';
|
|
94
|
+
const goal = segs[0] && segs[0] !== rb && !segs[0].startsWith('[') ? segs[0] : '';
|
|
95
|
+
const [repo = '', ...br] = rb.split('@');
|
|
96
|
+
sessions.push({ id, machine: parts[0] ?? '', name: parts.slice(1, -1).join(' · '), goal, repo, branch: br.join('@'), status: m[1] as 'live' | 'dormant' });
|
|
97
|
+
}
|
|
98
|
+
return sessions;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function buildFleetView(inputs: FleetInputs): FleetView {
|
|
102
|
+
const roles = parseRoles(inputs.roles ?? '');
|
|
103
|
+
const loops = parseLoops(inputs.loops ?? '');
|
|
104
|
+
const sessions = parseBridgeFind(inputs.sessions ?? '');
|
|
105
|
+
const ports = parsePorts(inputs.ports ?? '');
|
|
106
|
+
const byId = new Map(sessions.map((s) => [s.id, s]));
|
|
107
|
+
const used = new Set<string>();
|
|
108
|
+
const take = (id: string | null) => { const s = id ? byId.get(id) ?? null : null; if (s) used.add(s.id); return s; };
|
|
109
|
+
let relay: FleetSession | null = null;
|
|
110
|
+
const leads: FleetLead[] = [];
|
|
111
|
+
for (const row of roles.rows) {
|
|
112
|
+
if (/^relay$/i.test(row.role)) { relay = take(row.sessionId); continue; }
|
|
113
|
+
let session = take(row.sessionId);
|
|
114
|
+
// roles.md is hand-edited and runs behind: when the listed id is not live, a live session named for the role stands in
|
|
115
|
+
if (!session && row.role.length > 3) {
|
|
116
|
+
const named = sessions.find((s) => !used.has(s.id) && s.status === 'live' && s.name.toLowerCase().startsWith(row.role.toLowerCase()));
|
|
117
|
+
if (named) { used.add(named.id); session = named; }
|
|
118
|
+
}
|
|
119
|
+
leads.push({ role: row.role, notes: row.notes, listedId: row.sessionId && session?.id !== row.sessionId ? row.sessionId : undefined, session, children: row.childIds.map((id) => take(id)).filter((s): s is FleetSession => !!s) });
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
relay, leads, others: sessions.filter((s) => !used.has(s.id)),
|
|
123
|
+
waitingOnQuinn: loops.waitingOnQuinn, waitingOnSessions: loops.waitingOnSessions,
|
|
124
|
+
rolesUpdated: roles.updated, loopsUpdated: loops.updated, ports, sections: loops.sections, unparsed: [...roles.unparsed, ...loops.unparsed],
|
|
125
|
+
};
|
|
126
|
+
}
|