osborn 0.9.254 → 0.9.255
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/dist/index.js +54 -0
- package/dist/noise-gate.d.ts +64 -0
- package/dist/noise-gate.js +191 -0
- package/dist/pipeline-direct-llm.js +68 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -46,6 +46,7 @@ import { MCP_CATALOG } from './config.js';
|
|
|
46
46
|
import { getRecallClient } from './recall-client.js';
|
|
47
47
|
import { MeetingTranscriptPoller } from './meeting-transcript-poller.js';
|
|
48
48
|
import { missingRequiredEnv } from './env-keys.js';
|
|
49
|
+
import { noiseGate } from './noise-gate.js';
|
|
49
50
|
import { listSecretStatus, setSecrets, deleteSecret } from './secrets-store.js';
|
|
50
51
|
import { llm } from '@livekit/agents';
|
|
51
52
|
// ============================================================
|
|
@@ -3206,6 +3207,26 @@ async function main() {
|
|
|
3206
3207
|
// recovers — the user hears nothing for the rest of the connection. Keep these low.
|
|
3207
3208
|
const MAX_MESSAGE_SIZE = 30000; // 30KB soft limit — truncate text/content fields
|
|
3208
3209
|
const HARD_MAX_MESSAGE_SIZE = 50000; // 50KB hard limit — drop if still too large after truncation
|
|
3210
|
+
// ── Noise-gate wiring (once per session scope) ────────────────────────────
|
|
3211
|
+
// state → frontend toggle sync; drop → tombstone in the UI (never silently
|
|
3212
|
+
// lost); auto_exit (5 min quiet) → back to full conversation + a NON-
|
|
3213
|
+
// interrupting resume note ([SYSTEM prefix keeps it off priority 'now') so
|
|
3214
|
+
// the agent speaks first and picks the thread back up.
|
|
3215
|
+
noiseGate.removeAllListeners();
|
|
3216
|
+
noiseGate.on('state', (s) => {
|
|
3217
|
+
void sendToFrontend({ type: 'noise_cancel_state', enabled: s.enabled, reason: s.reason });
|
|
3218
|
+
});
|
|
3219
|
+
noiseGate.on('drop', (d) => {
|
|
3220
|
+
void sendToFrontend({ type: 'gate_dropped', text: d.text, verdict: d.verdict, ts: d.ts });
|
|
3221
|
+
});
|
|
3222
|
+
noiseGate.on('auto_exit', () => {
|
|
3223
|
+
try {
|
|
3224
|
+
currentLLM?.sendPrompt?.('[SYSTEM note — noise-cancellation mode auto-exited after ~5 minutes of quiet. ' +
|
|
3225
|
+
'The user has been silent and the room is back to normal voice conversation. ' +
|
|
3226
|
+
'Resume naturally: briefly check in out loud and mention anything useful that finished while they were away.]');
|
|
3227
|
+
}
|
|
3228
|
+
catch { }
|
|
3229
|
+
});
|
|
3209
3230
|
async function sendToFrontend(data) {
|
|
3210
3231
|
if (!localParticipant) {
|
|
3211
3232
|
console.log('⚠️ sendToFrontend: no localParticipant!');
|
|
@@ -5619,6 +5640,39 @@ async function main() {
|
|
|
5619
5640
|
}
|
|
5620
5641
|
}
|
|
5621
5642
|
}
|
|
5643
|
+
// Noise cancellation (noise gate) — UI toggle. Meeting chunks auto-engage
|
|
5644
|
+
// it pipeline-side; this is the explicit button next to mute.
|
|
5645
|
+
// FORWARD COUPLING: the agent's loaded meeting skill already knows how to
|
|
5646
|
+
// enter meeting-mode behavior on its own (it auto-detects multi-speaker
|
|
5647
|
+
// rooms without Recall) — so the toggle also tells the agent, via a
|
|
5648
|
+
// non-interrupting [SYSTEM note (never priority 'now'), to switch its
|
|
5649
|
+
// conversational behavior in the same direction.
|
|
5650
|
+
else if (data.type === 'noise_cancel') {
|
|
5651
|
+
const turningOn = !!data.enabled;
|
|
5652
|
+
const wasOn = noiseGate.enabled;
|
|
5653
|
+
noiseGate.setEnabled(turningOn, 'ui');
|
|
5654
|
+
await sendToFrontend({ type: 'noise_cancel_state', enabled: noiseGate.enabled, reason: noiseGate.reason });
|
|
5655
|
+
if (noiseGate.enabled !== wasOn) {
|
|
5656
|
+
try {
|
|
5657
|
+
currentLLM?.sendPrompt?.(turningOn
|
|
5658
|
+
? '[SYSTEM note — the user enabled noise-cancellation mode: they are in a noisy, multi-speaker environment (other conversations around them). Enter your meeting-mode behavior now even though no Recall meeting is connected: listen more than you speak, keep spoken replies short and only when clearly addressed, and expect filtered/sparse transcripts. Do not read this note aloud.]'
|
|
5659
|
+
: '[SYSTEM note — the user disabled noise-cancellation mode: the room is back to a normal one-on-one voice conversation. Exit meeting-mode behavior and resume normal conversational responses. Do not read this note aloud.]');
|
|
5660
|
+
}
|
|
5661
|
+
catch { }
|
|
5662
|
+
}
|
|
5663
|
+
}
|
|
5664
|
+
// Tombstone recovery — "send anyway" on a gate-dropped utterance. The text
|
|
5665
|
+
// is allow-listed for one pass so the gate can't re-drop it.
|
|
5666
|
+
else if (data.type === 'gate_send_anyway' && currentLLM) {
|
|
5667
|
+
const text = String(data.text || '').trim();
|
|
5668
|
+
if (text) {
|
|
5669
|
+
noiseGate.allowOnce(text);
|
|
5670
|
+
try {
|
|
5671
|
+
currentLLM.sendPrompt?.(text);
|
|
5672
|
+
}
|
|
5673
|
+
catch { }
|
|
5674
|
+
}
|
|
5675
|
+
}
|
|
5622
5676
|
// Feature B — per-flow stop (does NOT affect other running flows).
|
|
5623
5677
|
// Real now: stopAgent resolves agent_id → SDK task_id and issues
|
|
5624
5678
|
// query.stopTask (perTaskStopAffordance pairing). `stopped` is truthful —
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Noise gate ("noise cancellation" mode) — transcript triage BEFORE the main agent.
|
|
3
|
+
*
|
|
4
|
+
* Design (docs/noise-gate-research-2026-10.md + locked decisions):
|
|
5
|
+
* - Scope v1: competing CONVERSATIONS (classroom, taxi, multi-conversation rooms).
|
|
6
|
+
* Music/TV are out of scope — the user mutes manually for those.
|
|
7
|
+
* - The gate is a tiny LABEL-ONLY classifier call: no tools, no memory search,
|
|
8
|
+
* static system prompt (cache-friendly), ~1 word out. It never rewrites —
|
|
9
|
+
* a forwarded utterance is always the user's verbatim transcript.
|
|
10
|
+
* - FAIL-OPEN: any error/timeout forwards the utterance. A broken gate must
|
|
11
|
+
* degrade to today's behavior, never to a deaf agent. 'ambiguous' also
|
|
12
|
+
* forwards in v1 (false-reject costs more than false-accept; the ask-the-user
|
|
13
|
+
* UX is a later phase).
|
|
14
|
+
* - Drops are TOMBSTONED, never deleted: kept in a ring buffer and emitted to
|
|
15
|
+
* the frontend so a false drop costs one tap ("send anyway"), not lost words.
|
|
16
|
+
* - Toggles: UI button ('ui') and meeting-mode auto-engage ('meeting').
|
|
17
|
+
* - Silence auto-exit: after SILENCE_EXIT_MS with no gate activity, the gate
|
|
18
|
+
* turns itself off and emits 'auto_exit' — index.ts then tells the agent to
|
|
19
|
+
* resume the conversation (non-interrupting [SYSTEM note, never priority
|
|
20
|
+
* 'now') and notifies the frontend.
|
|
21
|
+
*
|
|
22
|
+
* Latency budget: the gate sits IN-LINE in front of the agent, and the fast
|
|
23
|
+
* brain's own loop has an 8s wall-clock deadline downstream — so the gate's
|
|
24
|
+
* deadline is short (default 2s) and strictly fail-open.
|
|
25
|
+
*/
|
|
26
|
+
import { EventEmitter } from 'node:events';
|
|
27
|
+
export type GateVerdict = 'directed' | 'side_talk' | 'ambiguous';
|
|
28
|
+
export declare const GATE_CONTEXT_TURNS: number;
|
|
29
|
+
export interface GateContext {
|
|
30
|
+
recentTurns: Array<{
|
|
31
|
+
role: string;
|
|
32
|
+
content: string;
|
|
33
|
+
}>;
|
|
34
|
+
activeWork: string;
|
|
35
|
+
}
|
|
36
|
+
export interface GateDrop {
|
|
37
|
+
text: string;
|
|
38
|
+
verdict: GateVerdict;
|
|
39
|
+
ts: number;
|
|
40
|
+
}
|
|
41
|
+
declare class NoiseGate extends EventEmitter {
|
|
42
|
+
#private;
|
|
43
|
+
enabled: boolean;
|
|
44
|
+
reason: 'ui' | 'meeting' | null;
|
|
45
|
+
/** Turn the gate on/off. reason 'ui' = button, 'meeting' = meeting-mode auto-engage. */
|
|
46
|
+
setEnabled(on: boolean, reason?: 'ui' | 'meeting' | 'silence'): void;
|
|
47
|
+
allowOnce(text: string): void;
|
|
48
|
+
/** True when this utterance should be triaged. Bracket-prefixed texts are
|
|
49
|
+
* synthetic ([MEETING/[SYSTEM/[INTERRUPTED templates), never raw user voice. */
|
|
50
|
+
shouldGate(text: string): boolean;
|
|
51
|
+
/** Any pass-through / meeting chunk counts as activity for the silence timer. */
|
|
52
|
+
noteActivity(): void;
|
|
53
|
+
recordDrop(text: string, verdict: GateVerdict): void;
|
|
54
|
+
getDropped(): GateDrop[];
|
|
55
|
+
/**
|
|
56
|
+
* Label-only classification. Fail-open: ANY failure (no key, HTTP error,
|
|
57
|
+
* timeout, unparseable label) returns 'directed' so the gate can never
|
|
58
|
+
* silence the user.
|
|
59
|
+
*/
|
|
60
|
+
classify(text: string, ctx: GateContext): Promise<GateVerdict>;
|
|
61
|
+
}
|
|
62
|
+
/** Singleton — one gate per agent process (one voice session per machine). */
|
|
63
|
+
export declare const noiseGate: NoiseGate;
|
|
64
|
+
export {};
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Noise gate ("noise cancellation" mode) — transcript triage BEFORE the main agent.
|
|
3
|
+
*
|
|
4
|
+
* Design (docs/noise-gate-research-2026-10.md + locked decisions):
|
|
5
|
+
* - Scope v1: competing CONVERSATIONS (classroom, taxi, multi-conversation rooms).
|
|
6
|
+
* Music/TV are out of scope — the user mutes manually for those.
|
|
7
|
+
* - The gate is a tiny LABEL-ONLY classifier call: no tools, no memory search,
|
|
8
|
+
* static system prompt (cache-friendly), ~1 word out. It never rewrites —
|
|
9
|
+
* a forwarded utterance is always the user's verbatim transcript.
|
|
10
|
+
* - FAIL-OPEN: any error/timeout forwards the utterance. A broken gate must
|
|
11
|
+
* degrade to today's behavior, never to a deaf agent. 'ambiguous' also
|
|
12
|
+
* forwards in v1 (false-reject costs more than false-accept; the ask-the-user
|
|
13
|
+
* UX is a later phase).
|
|
14
|
+
* - Drops are TOMBSTONED, never deleted: kept in a ring buffer and emitted to
|
|
15
|
+
* the frontend so a false drop costs one tap ("send anyway"), not lost words.
|
|
16
|
+
* - Toggles: UI button ('ui') and meeting-mode auto-engage ('meeting').
|
|
17
|
+
* - Silence auto-exit: after SILENCE_EXIT_MS with no gate activity, the gate
|
|
18
|
+
* turns itself off and emits 'auto_exit' — index.ts then tells the agent to
|
|
19
|
+
* resume the conversation (non-interrupting [SYSTEM note, never priority
|
|
20
|
+
* 'now') and notifies the frontend.
|
|
21
|
+
*
|
|
22
|
+
* Latency budget: the gate sits IN-LINE in front of the agent, and the fast
|
|
23
|
+
* brain's own loop has an 8s wall-clock deadline downstream — so the gate's
|
|
24
|
+
* deadline is short (default 2s) and strictly fail-open.
|
|
25
|
+
*/
|
|
26
|
+
import { EventEmitter } from 'node:events';
|
|
27
|
+
const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions';
|
|
28
|
+
const GATE_MODEL = process.env.OSBORN_GATE_MODEL || process.env.OSBORN_FAST_BRAIN_MODEL || 'deepseek/deepseek-chat';
|
|
29
|
+
const GATE_TIMEOUT_MS = Number(process.env.OSBORN_GATE_TIMEOUT_MS || 2000);
|
|
30
|
+
const SILENCE_EXIT_MS = Number(process.env.OSBORN_GATE_SILENCE_EXIT_MS || 5 * 60_000);
|
|
31
|
+
// Context depth: how many recent user/assistant turns the classifier sees.
|
|
32
|
+
// Research (docs/noise-gate-research-2026-10.md §4): conversational context is
|
|
33
|
+
// the load-bearing signal — too shallow and side-talk about adjacent topics
|
|
34
|
+
// slips through / real work talk gets dropped. Deep by default, esp. for
|
|
35
|
+
// meeting mode where topics drift.
|
|
36
|
+
export const GATE_CONTEXT_TURNS = Math.min(60, Math.max(8, Number(process.env.OSBORN_GATE_CONTEXT_TURNS || 30)));
|
|
37
|
+
const DROP_RING_MAX = 50;
|
|
38
|
+
// Static system prompt — keep byte-stable (prompt caching is prefix-matched).
|
|
39
|
+
const GATE_SYSTEM_PROMPT = [
|
|
40
|
+
'You are a transcript gate for a voice AI assistant worn as an earpiece in public.',
|
|
41
|
+
'Everything the microphone hears is transcribed and shown to you one utterance at a time.',
|
|
42
|
+
'The environment contains other people talking: teachers, taxi drivers, nearby conversations.',
|
|
43
|
+
'Your ONLY job: decide whether the utterance is directed at the assistant.',
|
|
44
|
+
'',
|
|
45
|
+
'Reply with EXACTLY one word:',
|
|
46
|
+
'- directed → the user is talking to the assistant (continues the current work/conversation, addresses it, asks it something, gives it instructions, or reacts to what it said)',
|
|
47
|
+
'- side_talk → clearly someone else talking, or the user talking to another person (greetings to others, classroom lecture content unrelated to the work, transactional talk like addresses/payments, conversational replies that make no sense addressed to an AI assistant)',
|
|
48
|
+
'- ambiguous → genuinely unclear',
|
|
49
|
+
'',
|
|
50
|
+
'Bias: when the utterance plausibly relates to the current work context, prefer directed.',
|
|
51
|
+
'Short backchannels ("yeah", "okay", "mhm") during active assistant work are directed.',
|
|
52
|
+
'Never reply with anything except one of the three labels.',
|
|
53
|
+
].join('\n');
|
|
54
|
+
class NoiseGate extends EventEmitter {
|
|
55
|
+
enabled = false;
|
|
56
|
+
reason = null;
|
|
57
|
+
#lastActivityAt = 0;
|
|
58
|
+
#timer = null;
|
|
59
|
+
#dropped = [];
|
|
60
|
+
/** Kill switch (read lazily so tests/ops can flip it at runtime):
|
|
61
|
+
* OSBORN_NOISE_GATE=off disables the gate entirely — no triage, no
|
|
62
|
+
* meeting auto-engage — restoring pre-gate behavior without a republish. */
|
|
63
|
+
#killed() {
|
|
64
|
+
return process.env.OSBORN_NOISE_GATE === 'off';
|
|
65
|
+
}
|
|
66
|
+
/** Turn the gate on/off. reason 'ui' = button, 'meeting' = meeting-mode auto-engage. */
|
|
67
|
+
setEnabled(on, reason = 'ui') {
|
|
68
|
+
if (on && this.#killed()) {
|
|
69
|
+
console.log('🚪 [gate] enable ignored — OSBORN_NOISE_GATE=off');
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const was = this.enabled;
|
|
73
|
+
this.enabled = on;
|
|
74
|
+
this.reason = on ? (reason === 'silence' ? this.reason : reason) : null;
|
|
75
|
+
if (on) {
|
|
76
|
+
this.#lastActivityAt = Date.now();
|
|
77
|
+
if (!this.#timer) {
|
|
78
|
+
this.#timer = setInterval(() => this.#tick(), 30_000);
|
|
79
|
+
this.#timer.unref?.();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
else if (this.#timer) {
|
|
83
|
+
clearInterval(this.#timer);
|
|
84
|
+
this.#timer = null;
|
|
85
|
+
}
|
|
86
|
+
if (was !== on) {
|
|
87
|
+
console.log(`🚪 [gate] ${on ? 'ENABLED' : 'DISABLED'} (${reason})`);
|
|
88
|
+
this.emit('state', { enabled: on, reason: on ? this.reason : reason });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
// One-shot allowlist for tombstone recovery ("send anyway"): the resent text
|
|
92
|
+
// must pass the gate exactly once without re-triage.
|
|
93
|
+
#allowOnce = new Set();
|
|
94
|
+
allowOnce(text) {
|
|
95
|
+
this.#allowOnce.add(text);
|
|
96
|
+
}
|
|
97
|
+
/** True when this utterance should be triaged. Bracket-prefixed texts are
|
|
98
|
+
* synthetic ([MEETING/[SYSTEM/[INTERRUPTED templates), never raw user voice. */
|
|
99
|
+
shouldGate(text) {
|
|
100
|
+
if (this.#killed() || !this.enabled || !text?.trim() || text.startsWith('['))
|
|
101
|
+
return false;
|
|
102
|
+
if (this.#allowOnce.has(text)) {
|
|
103
|
+
this.#allowOnce.delete(text);
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
/** Any pass-through / meeting chunk counts as activity for the silence timer. */
|
|
109
|
+
noteActivity() {
|
|
110
|
+
this.#lastActivityAt = Date.now();
|
|
111
|
+
}
|
|
112
|
+
recordDrop(text, verdict) {
|
|
113
|
+
const drop = { text, verdict, ts: Date.now() };
|
|
114
|
+
this.#dropped.push(drop);
|
|
115
|
+
if (this.#dropped.length > DROP_RING_MAX)
|
|
116
|
+
this.#dropped.shift();
|
|
117
|
+
this.emit('drop', drop);
|
|
118
|
+
}
|
|
119
|
+
getDropped() {
|
|
120
|
+
return [...this.#dropped];
|
|
121
|
+
}
|
|
122
|
+
#tick() {
|
|
123
|
+
if (!this.enabled)
|
|
124
|
+
return;
|
|
125
|
+
if (Date.now() - this.#lastActivityAt >= SILENCE_EXIT_MS) {
|
|
126
|
+
console.log(`🚪 [gate] ${Math.round(SILENCE_EXIT_MS / 60000)} min of quiet — auto-exiting noise-cancellation`);
|
|
127
|
+
this.setEnabled(false, 'silence');
|
|
128
|
+
this.emit('auto_exit', { quietMs: Date.now() - this.#lastActivityAt });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Label-only classification. Fail-open: ANY failure (no key, HTTP error,
|
|
133
|
+
* timeout, unparseable label) returns 'directed' so the gate can never
|
|
134
|
+
* silence the user.
|
|
135
|
+
*/
|
|
136
|
+
async classify(text, ctx) {
|
|
137
|
+
const apiKey = process.env.OPENROUTER_API_KEY;
|
|
138
|
+
if (!apiKey)
|
|
139
|
+
return 'directed';
|
|
140
|
+
const started = Date.now();
|
|
141
|
+
try {
|
|
142
|
+
const recent = ctx.recentTurns
|
|
143
|
+
.slice(-GATE_CONTEXT_TURNS)
|
|
144
|
+
.map(t => `${t.role === 'user' ? 'USER' : 'ASSISTANT'}: ${String(t.content).slice(0, 300)}`)
|
|
145
|
+
.join('\n');
|
|
146
|
+
const controller = new AbortController();
|
|
147
|
+
const to = setTimeout(() => controller.abort(), GATE_TIMEOUT_MS);
|
|
148
|
+
const resp = await fetch(OPENROUTER_URL, {
|
|
149
|
+
method: 'POST',
|
|
150
|
+
headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
|
|
151
|
+
signal: controller.signal,
|
|
152
|
+
body: JSON.stringify({
|
|
153
|
+
model: GATE_MODEL,
|
|
154
|
+
max_tokens: 5,
|
|
155
|
+
temperature: 0,
|
|
156
|
+
messages: [
|
|
157
|
+
{ role: 'system', content: GATE_SYSTEM_PROMPT },
|
|
158
|
+
{
|
|
159
|
+
role: 'user',
|
|
160
|
+
content: [
|
|
161
|
+
`Current work with the assistant:\n${ctx.activeWork || '(none known)'}`,
|
|
162
|
+
``,
|
|
163
|
+
`Recent conversation:\n${recent || '(none)'}`,
|
|
164
|
+
``,
|
|
165
|
+
`New utterance heard by the microphone:\n"${text}"`,
|
|
166
|
+
``,
|
|
167
|
+
`Label:`,
|
|
168
|
+
].join('\n'),
|
|
169
|
+
},
|
|
170
|
+
],
|
|
171
|
+
}),
|
|
172
|
+
});
|
|
173
|
+
clearTimeout(to);
|
|
174
|
+
if (!resp.ok)
|
|
175
|
+
return 'directed';
|
|
176
|
+
const data = await resp.json();
|
|
177
|
+
const raw = String(data?.choices?.[0]?.message?.content || '').toLowerCase();
|
|
178
|
+
const verdict = raw.includes('side_talk') || raw.includes('side talk')
|
|
179
|
+
? 'side_talk'
|
|
180
|
+
: raw.includes('ambiguous') ? 'ambiguous' : 'directed';
|
|
181
|
+
console.log(`🚪 [gate] verdict=${verdict} (${Date.now() - started}ms) "${text.slice(0, 60)}"`);
|
|
182
|
+
return verdict;
|
|
183
|
+
}
|
|
184
|
+
catch (err) {
|
|
185
|
+
console.log(`🚪 [gate] classify failed (${Date.now() - started}ms, ${err?.name || err?.message}) — fail-open → directed`);
|
|
186
|
+
return 'directed';
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/** Singleton — one gate per agent process (one voice session per machine). */
|
|
191
|
+
export const noiseGate = new NoiseGate();
|
|
@@ -13,6 +13,11 @@ import { ClaudeLLM } from './claude-llm.js';
|
|
|
13
13
|
import { askPipelineFastBrain } from './pipeline-fastbrain.js';
|
|
14
14
|
import { storeExists, openStore, recentRows } from './session-store.js';
|
|
15
15
|
import { statusManager } from './status-manager.js';
|
|
16
|
+
import { noiseGate, GATE_CONTEXT_TURNS } from './noise-gate.js';
|
|
17
|
+
// Bypass marker for gate-approved contexts: the deferred gate stream re-enters
|
|
18
|
+
// chat() with the SAME chatCtx after a forward verdict; the marker makes the
|
|
19
|
+
// second pass skip the gate and run the normal (enrichment + Claude) path.
|
|
20
|
+
const gateApproved = new WeakSet();
|
|
16
21
|
// ============================================================
|
|
17
22
|
// SESSION TAIL — compact recent-conversation block prepended to every user turn
|
|
18
23
|
// so the orchestrator never loses the thread across context compaction.
|
|
@@ -114,6 +119,19 @@ export class PipelineDirectLLM extends llm.LLM {
|
|
|
114
119
|
hasActiveAgent() { return this.#claudeLLM.hasActiveQuery(); }
|
|
115
120
|
stopAgent(agentId) { return this.#claudeLLM.stopAgent(agentId); }
|
|
116
121
|
getRunningTasks() { return this.#claudeLLM.getRunningTasks(); }
|
|
122
|
+
/** Context for the noise-gate classifier: recent turns + what's in flight.
|
|
123
|
+
* Research finding: conversational context is the load-bearing signal for
|
|
124
|
+
* addressee detection (its absence roughly halves F1). */
|
|
125
|
+
#buildGateContext() {
|
|
126
|
+
const recentTurns = (this.#opts.getChatHistory?.() || []).slice(-GATE_CONTEXT_TURNS);
|
|
127
|
+
const dispatches = statusManager.getActiveDispatches();
|
|
128
|
+
const tasks = this.#claudeLLM.getRunningTasks();
|
|
129
|
+
const activeWork = [
|
|
130
|
+
dispatches.length ? `active sub-agents: ${dispatches.map(d => d.subagentType || 'agent').join(', ')}` : '',
|
|
131
|
+
tasks.length ? `running tasks: ${tasks.map(t => `${t.subagentType || 'task'}: ${(t.description || '').slice(0, 80)}`).join('; ')}` : '',
|
|
132
|
+
].filter(Boolean).join(' | ');
|
|
133
|
+
return { recentTurns, activeWork };
|
|
134
|
+
}
|
|
117
135
|
/** Send a new prompt to Claude via direct chat() — event listeners stay attached */
|
|
118
136
|
sendPrompt(prompt) {
|
|
119
137
|
console.log(`📋 [pipeline] Sending prompt to Claude (${prompt.length} chars)`);
|
|
@@ -143,6 +161,27 @@ export class PipelineDirectLLM extends llm.LLM {
|
|
|
143
161
|
}
|
|
144
162
|
}
|
|
145
163
|
console.log(`📥 [pipeline] chat() call #${callN} (${userText.length} chars): "${userText}"`);
|
|
164
|
+
// ── NOISE GATE (noise-cancellation mode) ─────────────────────────────────
|
|
165
|
+
// Triage BEFORE any enrichment: a dropped stranger utterance must never
|
|
166
|
+
// consume pending interruption context, fire an interrupt, or reach the
|
|
167
|
+
// agent/fast brain. chat() stays synchronous (LiveKit contract) — the gate
|
|
168
|
+
// returns a deferred stream that re-enters chat() with a bypass marker on
|
|
169
|
+
// forward. Fail-open: classifier error/timeout forwards verbatim.
|
|
170
|
+
if (noiseGate.shouldGate(userText) && !gateApproved.has(chatCtx)) {
|
|
171
|
+
console.log(`🚪 [gate] holding utterance for triage: "${userText.slice(0, 60)}"`);
|
|
172
|
+
return new NoiseGateStream(this, { chatCtx, toolCtx, connOptions }, async () => {
|
|
173
|
+
const verdict = await noiseGate.classify(userText, this.#buildGateContext());
|
|
174
|
+
if (verdict === 'side_talk') {
|
|
175
|
+
noiseGate.recordDrop(userText, verdict);
|
|
176
|
+
console.log(`🚪 [gate] dropped side_talk: "${userText.slice(0, 60)}"`);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
// directed | ambiguous → forward the VERBATIM text through the normal path
|
|
180
|
+
noiseGate.noteActivity();
|
|
181
|
+
gateApproved.add(chatCtx);
|
|
182
|
+
this.chat({ chatCtx, toolCtx, connOptions, abortController });
|
|
183
|
+
});
|
|
184
|
+
}
|
|
146
185
|
// ── SESSION TAIL injection (seam-only) ───────────────────────────────────
|
|
147
186
|
// Inject the tail ONCE on the first real user turn after a compaction
|
|
148
187
|
// completes. Never injected on every turn (avoids catastrophic accumulation
|
|
@@ -304,6 +343,14 @@ export class PipelineDirectLLM extends llm.LLM {
|
|
|
304
343
|
// it. Cleared implicitly by the next real user turn (which isn't a [MEETING]).
|
|
305
344
|
const isMeetingChunk = userText.startsWith('[MEETING');
|
|
306
345
|
this.suppressMeetingTTS = isMeetingChunk;
|
|
346
|
+
// Meeting mode ⇄ noise cancellation coupling: meeting chunks auto-engage the
|
|
347
|
+
// gate (same detection the user already relies on) and count as activity so
|
|
348
|
+
// the silence auto-exit doesn't fire mid-meeting while the user listens.
|
|
349
|
+
if (isMeetingChunk) {
|
|
350
|
+
if (!noiseGate.enabled)
|
|
351
|
+
noiseGate.setEnabled(true, 'meeting');
|
|
352
|
+
noiseGate.noteActivity();
|
|
353
|
+
}
|
|
307
354
|
// Fire Claude
|
|
308
355
|
const claudeStream = this.#claudeLLM.chat({ chatCtx, toolCtx, connOptions, abortController });
|
|
309
356
|
// Fire pipeline fast brain in background — no await, no blocking. Skip for
|
|
@@ -394,6 +441,27 @@ export class PipelineDirectLLM extends llm.LLM {
|
|
|
394
441
|
}
|
|
395
442
|
}
|
|
396
443
|
}
|
|
444
|
+
// Deferred stream returned while the noise gate triages an utterance. Satisfies
|
|
445
|
+
// the synchronous chat() → llm.LLMStream contract (LiveKit); run() resolves the
|
|
446
|
+
// verdict and either drops (tombstoned by the gate) or re-enters chat() with the
|
|
447
|
+
// bypass marker so the full normal path (enrichment, Claude, fast brain) runs.
|
|
448
|
+
// Mirrors ClaudeLLMStream's direct-mode shape: run() returns quickly and the
|
|
449
|
+
// pipeline is released; the real reply flows via tts_say/assistant events.
|
|
450
|
+
class NoiseGateStream extends llm.LLMStream {
|
|
451
|
+
#task;
|
|
452
|
+
constructor(llmInstance, { chatCtx, toolCtx, connOptions }, task) {
|
|
453
|
+
super(llmInstance, { chatCtx, toolCtx, connOptions });
|
|
454
|
+
this.#task = task;
|
|
455
|
+
}
|
|
456
|
+
async run() {
|
|
457
|
+
try {
|
|
458
|
+
await this.#task();
|
|
459
|
+
}
|
|
460
|
+
catch (err) {
|
|
461
|
+
console.warn('🚪 [gate] deferred stream error (fail-open already applied upstream):', err?.message);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
397
465
|
export function createPipelineDirectLLM(opts) {
|
|
398
466
|
return new PipelineDirectLLM(opts);
|
|
399
467
|
}
|