osborn 0.9.253 → 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/claude-llm.d.ts +2 -0
- package/dist/claude-llm.js +31 -3
- package/dist/index.js +69 -5
- package/dist/noise-gate.d.ts +64 -0
- package/dist/noise-gate.js +191 -0
- package/dist/pipeline-direct-llm.d.ts +6 -0
- package/dist/pipeline-direct-llm.js +76 -1
- package/package.json +1 -1
package/dist/claude-llm.d.ts
CHANGED
|
@@ -190,6 +190,8 @@ export declare class ClaudeLLM extends llm.LLM {
|
|
|
190
190
|
setTurbo(on: boolean): void;
|
|
191
191
|
/** Read-only accessor used by ClaudeLLMStream (private fields are class-scoped). */
|
|
192
192
|
get turbo(): boolean;
|
|
193
|
+
permissionPending: boolean;
|
|
194
|
+
compacting: boolean;
|
|
193
195
|
/**
|
|
194
196
|
* Set session ID to resume a specific conversation
|
|
195
197
|
* Call this before sending the first message to resume from a previous session
|
package/dist/claude-llm.js
CHANGED
|
@@ -1321,6 +1321,13 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1321
1321
|
}
|
|
1322
1322
|
/** Read-only accessor used by ClaudeLLMStream (private fields are class-scoped). */
|
|
1323
1323
|
get turbo() { return this.#turbo; }
|
|
1324
|
+
// Steer-priority suppression state (adversarial findings #1/#8): a 'now'
|
|
1325
|
+
// message aborts the running turn, so never stamp it while that turn is
|
|
1326
|
+
// parked on a permission dialog (the user's spoken "yes, allow it" would
|
|
1327
|
+
// abort the asking turn) or while the session is compacting (repeated
|
|
1328
|
+
// voice chatter could cancel compaction over and over).
|
|
1329
|
+
permissionPending = false;
|
|
1330
|
+
compacting = false;
|
|
1324
1331
|
/**
|
|
1325
1332
|
* Set session ID to resume a specific conversation
|
|
1326
1333
|
* Call this before sending the first message to resume from a previous session
|
|
@@ -1745,7 +1752,10 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1745
1752
|
const pending = this.#pendingInterrupt;
|
|
1746
1753
|
if (pending) {
|
|
1747
1754
|
console.log('⚡ Persistent session: interrupt in flight — deferring push until it settles');
|
|
1748
|
-
|
|
1755
|
+
// Deadline (adversarial finding #2): a wedged interrupt control request
|
|
1756
|
+
// must not make the agent permanently deaf — push anyway after 8s.
|
|
1757
|
+
const deadline = new Promise((res) => setTimeout(res, 8000));
|
|
1758
|
+
Promise.race([pending, deadline]).then(() => {
|
|
1749
1759
|
if (this.#messageChannel && !this.#messageChannel.closed) {
|
|
1750
1760
|
console.log('⚡ Persistent session: pushing deferred message (post-interrupt)');
|
|
1751
1761
|
this.#messageChannel.push(userMessage);
|
|
@@ -1839,6 +1849,7 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1839
1849
|
if (msg.type === 'system' && msg.subtype === 'status') {
|
|
1840
1850
|
const status = msg.status;
|
|
1841
1851
|
if (status === 'compacting' || status === null) {
|
|
1852
|
+
this.compacting = status === 'compacting';
|
|
1842
1853
|
console.log(`[COMPACT-SDK-ITER] status change: ${status === 'compacting' ? 'ENTERED compacting' : 'EXITED compacting'} session=${msg.session_id?.substring(0, 8) ?? '?'}`);
|
|
1843
1854
|
}
|
|
1844
1855
|
}
|
|
@@ -1899,6 +1910,11 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1899
1910
|
this.#currentTurnChunkIndex = 0;
|
|
1900
1911
|
this.#currentTurnChunks = [];
|
|
1901
1912
|
this.#currentTurnSpeed = undefined;
|
|
1913
|
+
// Stale-dispatch pruning (adversarial finding #6): any Task dispatch id
|
|
1914
|
+
// still unclaimed at turn end never reached SubagentStart (denied,
|
|
1915
|
+
// errored, or its turn aborted) — drop it so it can't poison the next
|
|
1916
|
+
// agent_id pairing of the same type.
|
|
1917
|
+
this.#pendingToolUseByType.clear();
|
|
1902
1918
|
console.log('✅ Claude turn complete (persistent session stays alive)');
|
|
1903
1919
|
}
|
|
1904
1920
|
}
|
|
@@ -2120,7 +2136,15 @@ class ClaudeLLMStream extends llm.LLMStream {
|
|
|
2120
2136
|
return { behavior: 'deny', message: 'Research mode does not use plan mode. Just proceed with the research directly.' };
|
|
2121
2137
|
}
|
|
2122
2138
|
console.log(`⚠️ Permission needed: ${toolName}`);
|
|
2123
|
-
|
|
2139
|
+
// Track the pending dialog so steer-priority ('now') suppression can
|
|
2140
|
+
// avoid aborting the very turn that's waiting on the user's answer.
|
|
2141
|
+
this.#llmRef.permissionPending = true;
|
|
2142
|
+
try {
|
|
2143
|
+
return await this.#onPermissionRequest(toolName, input);
|
|
2144
|
+
}
|
|
2145
|
+
finally {
|
|
2146
|
+
this.#llmRef.permissionPending = false;
|
|
2147
|
+
}
|
|
2124
2148
|
},
|
|
2125
2149
|
hooks: {
|
|
2126
2150
|
PreToolUse: [{
|
|
@@ -2701,7 +2725,11 @@ class ClaudeLLMStream extends llm.LLMStream {
|
|
|
2701
2725
|
// Meeting transcript chunks are ambient and must NOT interrupt (they
|
|
2702
2726
|
// arrive continuously and would abort working turns nonstop).
|
|
2703
2727
|
// Escape hatch: OSBORN_MSG_PRIORITY=off restores queue-and-fold.
|
|
2704
|
-
const steerNow = process.env.OSBORN_MSG_PRIORITY !== 'off'
|
|
2728
|
+
const steerNow = process.env.OSBORN_MSG_PRIORITY !== 'off'
|
|
2729
|
+
&& !userText.startsWith('[MEETING') // ambient transcript chunks never abort a turn
|
|
2730
|
+
&& !userText.startsWith('[SYSTEM') // join/end notes etc. never abort a turn
|
|
2731
|
+
&& !this.#llmRef.permissionPending // don't abort the turn awaiting the user's answer
|
|
2732
|
+
&& !this.#llmRef.compacting; // don't cancel an in-flight compaction
|
|
2705
2733
|
this.#llmRef.pushMessage(userText, sdkOptions, {
|
|
2706
2734
|
onSessionId: this.#onSessionId,
|
|
2707
2735
|
onCheckpoint: this.#onCheckpoint,
|
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 —
|
|
@@ -5639,8 +5693,16 @@ async function main() {
|
|
|
5639
5693
|
}
|
|
5640
5694
|
catch { }
|
|
5641
5695
|
}
|
|
5642
|
-
// Always confirm so frontend clears the card (covers ghost/stale flows too)
|
|
5643
|
-
|
|
5696
|
+
// Always confirm so frontend clears the card (covers ghost/stale flows too).
|
|
5697
|
+
// runningTasks lets the frontend tell a ghost row (0 → safe to clear)
|
|
5698
|
+
// from a live-but-uncorrelated runaway (>0 → keep the row visible).
|
|
5699
|
+
const runningTasks = (() => { try {
|
|
5700
|
+
return currentLLM.getRunningTasks?.()?.length ?? 0;
|
|
5701
|
+
}
|
|
5702
|
+
catch {
|
|
5703
|
+
return 0;
|
|
5704
|
+
} })();
|
|
5705
|
+
await sendToFrontend({ type: 'agent_stopped', agent_id: agentId, stopped, runningTasks });
|
|
5644
5706
|
}
|
|
5645
5707
|
else if (data.type === 'join_meeting') {
|
|
5646
5708
|
const meetingUrl = data.url;
|
|
@@ -5926,9 +5988,11 @@ async function main() {
|
|
|
5926
5988
|
slot.dispatchInFlight = true;
|
|
5927
5989
|
// Reuse the cold-start emitter — pushMessage's fast path ignores a
|
|
5928
5990
|
// fresh emitter once the subprocess exists (see spawnBackgroundSession).
|
|
5929
|
-
//
|
|
5930
|
-
//
|
|
5931
|
-
|
|
5991
|
+
// NO priority override here (adversarial finding #4): slot work is
|
|
5992
|
+
// FOREGROUND turn work — a 'now' dispatch would abort the previous
|
|
5993
|
+
// instruction mid-flight and corrupt dispatchInFlight accounting.
|
|
5994
|
+
// Instructions queue/fold like before.
|
|
5995
|
+
slot.llm.pushMessage(instruction, slot.sdkOptions, { onSessionId: () => { }, onCheckpoint: () => { }, eventEmitter: slot.emitter });
|
|
5932
5996
|
void sendToFrontend({ type: 'background_dispatched', sessionId: targetSessionId, instruction });
|
|
5933
5997
|
};
|
|
5934
5998
|
if (slots.has(targetSessionId))
|
|
@@ -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();
|
|
@@ -69,6 +69,12 @@ export declare class PipelineDirectLLM extends llm.LLM {
|
|
|
69
69
|
rewindAgent(checkpointId?: string): Promise<boolean>;
|
|
70
70
|
hasActiveAgent(): boolean;
|
|
71
71
|
stopAgent(agentId: string): Promise<boolean>;
|
|
72
|
+
getRunningTasks(): {
|
|
73
|
+
taskId: string;
|
|
74
|
+
subagentType?: string;
|
|
75
|
+
description?: string;
|
|
76
|
+
status: string;
|
|
77
|
+
}[];
|
|
72
78
|
/** Send a new prompt to Claude via direct chat() — event listeners stay attached */
|
|
73
79
|
sendPrompt(prompt: string): void;
|
|
74
80
|
enableMcpServer(k: string, c: any): void;
|
|
@@ -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.
|
|
@@ -113,6 +118,20 @@ export class PipelineDirectLLM extends llm.LLM {
|
|
|
113
118
|
async rewindAgent(checkpointId) { return this.#claudeLLM.rewindToCheckpoint(checkpointId); }
|
|
114
119
|
hasActiveAgent() { return this.#claudeLLM.hasActiveQuery(); }
|
|
115
120
|
stopAgent(agentId) { return this.#claudeLLM.stopAgent(agentId); }
|
|
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
|
+
}
|
|
116
135
|
/** Send a new prompt to Claude via direct chat() — event listeners stay attached */
|
|
117
136
|
sendPrompt(prompt) {
|
|
118
137
|
console.log(`📋 [pipeline] Sending prompt to Claude (${prompt.length} chars)`);
|
|
@@ -142,6 +161,27 @@ export class PipelineDirectLLM extends llm.LLM {
|
|
|
142
161
|
}
|
|
143
162
|
}
|
|
144
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
|
+
}
|
|
145
185
|
// ── SESSION TAIL injection (seam-only) ───────────────────────────────────
|
|
146
186
|
// Inject the tail ONCE on the first real user turn after a compaction
|
|
147
187
|
// completes. Never injected on every turn (avoids catastrophic accumulation
|
|
@@ -169,7 +209,13 @@ export class PipelineDirectLLM extends llm.LLM {
|
|
|
169
209
|
// interrupting active TTS. We need to forward BOTH cases so the agent knows
|
|
170
210
|
// what it produced that the user didn't hear, and so the buffer is cleared
|
|
171
211
|
// every turn even when there was no interrupt.
|
|
172
|
-
|
|
212
|
+
// MEETING GUARD (adversarial finding): never consume/enrich interrupt context
|
|
213
|
+
// on a meeting transcript chunk — enrichment would prefix it [INTERRUPTED]/
|
|
214
|
+
// [CONTEXT] (defeating the downstream '[MEETING' priority guard) and fire
|
|
215
|
+
// interruptQuery() for a transcript chunk, aborting working turns nonstop.
|
|
216
|
+
// Leave the pending context for the next REAL user message.
|
|
217
|
+
const isMeetingChunkEarly = userText.startsWith('[MEETING');
|
|
218
|
+
const interruptCtx = isMeetingChunkEarly ? null : this.#opts.getAndConsumeInterruptionContext?.();
|
|
173
219
|
if (interruptCtx && userText.trim()) {
|
|
174
220
|
const hasInterrupt = !!interruptCtx.spokenText;
|
|
175
221
|
const hasSuppressed = !!interruptCtx.suppressedText;
|
|
@@ -297,6 +343,14 @@ export class PipelineDirectLLM extends llm.LLM {
|
|
|
297
343
|
// it. Cleared implicitly by the next real user turn (which isn't a [MEETING]).
|
|
298
344
|
const isMeetingChunk = userText.startsWith('[MEETING');
|
|
299
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
|
+
}
|
|
300
354
|
// Fire Claude
|
|
301
355
|
const claudeStream = this.#claudeLLM.chat({ chatCtx, toolCtx, connOptions, abortController });
|
|
302
356
|
// Fire pipeline fast brain in background — no await, no blocking. Skip for
|
|
@@ -387,6 +441,27 @@ export class PipelineDirectLLM extends llm.LLM {
|
|
|
387
441
|
}
|
|
388
442
|
}
|
|
389
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
|
+
}
|
|
390
465
|
export function createPipelineDirectLLM(opts) {
|
|
391
466
|
return new PipelineDirectLLM(opts);
|
|
392
467
|
}
|