osborn 0.9.274 → 0.9.276
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/.claude/skills/meetings/SKILL.md +1 -1
- package/dist/claude-auth.d.ts +93 -6
- package/dist/claude-auth.js +241 -27
- package/dist/claude-llm.d.ts +31 -1
- package/dist/claude-llm.js +147 -10
- package/dist/data-sender-auth.d.ts +1 -0
- package/dist/data-sender-auth.js +4 -0
- package/dist/duck.d.ts +8 -0
- package/dist/duck.js +59 -0
- package/dist/index.js +468 -123
- package/dist/lib/safe-artifact-path.d.ts +17 -0
- package/dist/lib/safe-artifact-path.js +129 -0
- package/dist/meeting-tts.d.ts +35 -0
- package/dist/meeting-tts.js +161 -0
- package/dist/pipeline-direct-llm.d.ts +36 -1
- package/dist/pipeline-direct-llm.js +110 -24
- package/dist/pipeline-fastbrain.d.ts +14 -0
- package/dist/pipeline-fastbrain.js +5 -3
- package/dist/prompts/direct-mode-research.md +2 -0
- package/dist/prompts.d.ts +1 -1
- package/dist/prompts.js +3 -0
- package/dist/session-switch.d.ts +151 -0
- package/dist/session-switch.js +188 -0
- package/package.json +1 -1
package/dist/claude-llm.js
CHANGED
|
@@ -16,6 +16,7 @@ import { openStore, recall, storeExists, updateSessionStore, getStorePath } from
|
|
|
16
16
|
import { appendCompactionRecord, countTranscriptRows } from './compaction-log.js';
|
|
17
17
|
import { getEmbedder } from './embedder.js';
|
|
18
18
|
import { launchCompactionLens } from './content/lens-launch.js';
|
|
19
|
+
import { isSafeArtifactPath } from './lib/safe-artifact-path.js';
|
|
19
20
|
import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, statSync } from 'node:fs';
|
|
20
21
|
import { join, dirname, resolve, basename } from 'node:path';
|
|
21
22
|
import { fileURLToPath } from 'node:url';
|
|
@@ -903,6 +904,31 @@ export const FAST_MODEL = 'haiku';
|
|
|
903
904
|
// alternatives: 'qwen/qwen3-coder' (a hair faster), 'moonshotai/kimi-k2.6',
|
|
904
905
|
// 'deepseek/deepseek-chat' (needs proxy — thinking mode breaks the tool loop)
|
|
905
906
|
export const FALLBACK_MODEL = 'minimax/minimax-m3'; // OpenRouter tier baseline
|
|
907
|
+
// ── Deferred restart after an auth-backend change ──
|
|
908
|
+
// The persistent SDK subprocess inherits process.env (ANTHROPIC_BASE_URL /
|
|
909
|
+
// AUTH_TOKEN / model overrides) once, at spawn. When the auth backend changes
|
|
910
|
+
// mid-session (on-demand Claude sign-in replaces the z.ai/OpenRouter fallback),
|
|
911
|
+
// a live subprocess would keep routing to the fallback. requestAuthRestart()
|
|
912
|
+
// bumps a generation counter; each ClaudeLLM remembers the generation its
|
|
913
|
+
// subprocess was spawned under and, at the START of its next turn (pushMessage,
|
|
914
|
+
// only when no turn is streaming), closes the stale subprocess and cold-starts
|
|
915
|
+
// with `resume: <same sessionId>`. Nothing is aborted at request time — a turn
|
|
916
|
+
// that is currently streaming finishes normally on the old backend.
|
|
917
|
+
let authEnvGeneration = 0;
|
|
918
|
+
export function requestAuthRestart() {
|
|
919
|
+
authEnvGeneration++;
|
|
920
|
+
console.log(`🔑 Auth backend changed — persistent sessions will restart before their next turn (gen ${authEnvGeneration})`);
|
|
921
|
+
return authEnvGeneration;
|
|
922
|
+
}
|
|
923
|
+
export function getAuthEnvGeneration() { return authEnvGeneration; }
|
|
924
|
+
/**
|
|
925
|
+
* Pure decision: restart a live persistent subprocess before pushing the next
|
|
926
|
+
* message? Only when it was spawned under an older auth generation AND it is
|
|
927
|
+
* idle (no turn streaming, no interrupt settling).
|
|
928
|
+
*/
|
|
929
|
+
export function shouldRestartForAuth(spawnGen, currentGen, turnsInFlight, interruptPending) {
|
|
930
|
+
return spawnGen !== currentGen && turnsInFlight <= 0 && !interruptPending;
|
|
931
|
+
}
|
|
906
932
|
/**
|
|
907
933
|
* Apply turbo override to an agents roster.
|
|
908
934
|
* When turbo is true returns a DEEP COPY with every agent's model set to
|
|
@@ -964,11 +990,14 @@ const WRITE_RULES = {
|
|
|
964
990
|
tester: { extensions: /\.(test|spec)\.[jt]sx?$/, label: 'test', matchBasename: true },
|
|
965
991
|
reviewer: { extensions: /\.(md|markdown|mdx|txt|rst|adoc)$/i, label: 'documentation' },
|
|
966
992
|
};
|
|
967
|
-
/**
|
|
993
|
+
/**
|
|
994
|
+
* Path is inside the per-session sandbox workspace. Used by decideWrite's
|
|
995
|
+
* 'workspace' rule: true → write allowed, false → denied. Robust resolve+root
|
|
996
|
+
* check (NOT a substring) so a `..` traversal path like `…/osb/../../etc/foo`
|
|
997
|
+
* can't masquerade as a workspace path and widen the allow surface.
|
|
998
|
+
*/
|
|
968
999
|
function isWorkspacePath(filePath) {
|
|
969
|
-
return
|
|
970
|
-
filePath.includes('.osborn/sessions/') ||
|
|
971
|
-
filePath.includes('.osborn/research/'));
|
|
1000
|
+
return isSafeArtifactPath(filePath);
|
|
972
1001
|
}
|
|
973
1002
|
/**
|
|
974
1003
|
* Decide a Write/Edit/MultiEdit for the acting agent (null = main orchestrator).
|
|
@@ -1200,6 +1229,20 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1200
1229
|
// settles, so an enriched [INTERRUPTED] message can never land inside the
|
|
1201
1230
|
// turn being aborted (a fold-in-flight message dies with that turn).
|
|
1202
1231
|
#pendingInterrupt = null;
|
|
1232
|
+
// Auth generation the persistent subprocess was spawned under, and the number
|
|
1233
|
+
// of pushed user messages whose turn has not produced a `result` yet. Together
|
|
1234
|
+
// they drive the deferred restart (see requestAuthRestart()).
|
|
1235
|
+
#spawnAuthGen = authEnvGeneration;
|
|
1236
|
+
#turnsInFlight = 0;
|
|
1237
|
+
// `resume` id the live persistent query was spawned with (null = fresh, or no
|
|
1238
|
+
// query). Lets a session switch tell "query already runs the armed target"
|
|
1239
|
+
// from "armed target is a pending switch" (#74; see session-switch.ts).
|
|
1240
|
+
#spawnedResumeId = null;
|
|
1241
|
+
#queryFn = query;
|
|
1242
|
+
/** True when the live subprocess predates the latest auth-backend change. */
|
|
1243
|
+
get authRestartPending() {
|
|
1244
|
+
return !!this.#persistentQuery && this.#spawnAuthGen !== authEnvGeneration;
|
|
1245
|
+
}
|
|
1203
1246
|
// Dedup guard — prevents double-firing reviewer/gate if SubagentStop fires
|
|
1204
1247
|
// more than once for the same agent_id (e.g. retry edge cases).
|
|
1205
1248
|
#dispatchedFor = new Set();
|
|
@@ -1250,6 +1293,8 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1250
1293
|
onCompactionEvent: opts.onCompactionEvent,
|
|
1251
1294
|
};
|
|
1252
1295
|
this.#eventEmitter = opts.eventEmitter || new EventEmitter();
|
|
1296
|
+
if (opts.queryFn)
|
|
1297
|
+
this.#queryFn = opts.queryFn;
|
|
1253
1298
|
console.log('🟠 ClaudeLLM initialized (Research Mode)');
|
|
1254
1299
|
console.log(` 📁 Working dir (cwd): ${this.#opts.workingDirectory}`);
|
|
1255
1300
|
if (this.#opts.sessionBaseDir !== this.#opts.workingDirectory) {
|
|
@@ -1442,6 +1487,9 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1442
1487
|
setWorkingDirectory(path) {
|
|
1443
1488
|
this.#opts.workingDirectory = path;
|
|
1444
1489
|
}
|
|
1490
|
+
get workingDirectory() {
|
|
1491
|
+
return this.#opts.workingDirectory;
|
|
1492
|
+
}
|
|
1445
1493
|
/**
|
|
1446
1494
|
* Reset state for mid-conversation session switch
|
|
1447
1495
|
* Clears pending permissions and resets conversation tracking
|
|
@@ -1594,6 +1642,16 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1594
1642
|
});
|
|
1595
1643
|
this.#pendingInterrupt = tracked;
|
|
1596
1644
|
await p;
|
|
1645
|
+
// Turn-in-flight reset (#90 leak fix): the interrupt aborts the current
|
|
1646
|
+
// turn and returns the subprocess to idle, but closeSession() is
|
|
1647
|
+
// deliberately NOT called here (the subprocess stays alive) and the
|
|
1648
|
+
// aborted turn may never emit a terminal `result` to decrement
|
|
1649
|
+
// #turnsInFlight. Without this reset the counter leaks upward forever,
|
|
1650
|
+
// permanently wedging shouldRestartForAuth() so a later Claude sign-in
|
|
1651
|
+
// never swaps the live subprocess off the fallback backend. Reset to 0
|
|
1652
|
+
// (not decrement): an idle subprocess has no turn streaming. Safe — the
|
|
1653
|
+
// result handler clamps at > 0, so a late `result` can't drive it negative.
|
|
1654
|
+
this.#turnsInFlight = 0;
|
|
1597
1655
|
console.log('🛑 Interrupted persistent session (Esc equivalent — subprocess stays alive)');
|
|
1598
1656
|
return true;
|
|
1599
1657
|
}
|
|
@@ -1821,6 +1879,27 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1821
1879
|
// start; subsequent chat() calls push messages to the existing
|
|
1822
1880
|
// subprocess via the MessageChannel — no JSONL replay.
|
|
1823
1881
|
// ============================================================
|
|
1882
|
+
/** `resume` id the live persistent query was spawned with (null = fresh / none). */
|
|
1883
|
+
get spawnedResumeId() {
|
|
1884
|
+
return this.#spawnedResumeId;
|
|
1885
|
+
}
|
|
1886
|
+
/**
|
|
1887
|
+
* What the live session is doing right now (#74). A session switch is only
|
|
1888
|
+
* executed when `idle`: a turn awaiting its result, SDK tasks (sub-agents
|
|
1889
|
+
* outlive their turn), compaction, an in-flight interrupt or a permission
|
|
1890
|
+
* prompt all mean closing the query would lose work.
|
|
1891
|
+
*/
|
|
1892
|
+
busyState() {
|
|
1893
|
+
const turnInFlight = this.#turnsInFlight > 0;
|
|
1894
|
+
const runningTasks = this.getRunningTasks().length;
|
|
1895
|
+
const compacting = !!this.compacting;
|
|
1896
|
+
const interruptPending = !!this.#pendingInterrupt;
|
|
1897
|
+
const permissionPending = this.hasPendingPermission();
|
|
1898
|
+
return {
|
|
1899
|
+
turnInFlight, runningTasks, compacting, interruptPending, permissionPending,
|
|
1900
|
+
idle: !turnInFlight && runningTasks === 0 && !compacting && !interruptPending && !permissionPending,
|
|
1901
|
+
};
|
|
1902
|
+
}
|
|
1824
1903
|
/** Whether a persistent session is alive and consuming messages */
|
|
1825
1904
|
hasSession() {
|
|
1826
1905
|
return this.#persistentQuery !== null && !this.#messageChannel?.closed;
|
|
@@ -1854,6 +1933,7 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1854
1933
|
}
|
|
1855
1934
|
this.#persistentQuery = null;
|
|
1856
1935
|
this.#messageChannel = null;
|
|
1936
|
+
this.#spawnedResumeId = null;
|
|
1857
1937
|
this.#backgroundConsumerRunning = false;
|
|
1858
1938
|
this.#dispatchedFor.clear();
|
|
1859
1939
|
// Task registry is per-process (SDK task ids die with the subprocess).
|
|
@@ -1863,6 +1943,7 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1863
1943
|
this.#toolUseByAgentId.clear();
|
|
1864
1944
|
this.#typeByAgentId.clear();
|
|
1865
1945
|
this.#pendingInterrupt = null;
|
|
1946
|
+
this.#turnsInFlight = 0;
|
|
1866
1947
|
console.log('🔒 Persistent session closed');
|
|
1867
1948
|
}
|
|
1868
1949
|
/**
|
|
@@ -1894,8 +1975,10 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1894
1975
|
return;
|
|
1895
1976
|
}
|
|
1896
1977
|
console.log('🔥 primeResume: eager cold-start — resume replay overlaps connect (no user message)');
|
|
1978
|
+
this.#spawnAuthGen = authEnvGeneration;
|
|
1897
1979
|
this.#messageChannel = new MessageChannel();
|
|
1898
|
-
this.#
|
|
1980
|
+
this.#spawnedResumeId = sdkOptions?.resume ?? null;
|
|
1981
|
+
this.#persistentQuery = this.#queryFn({ prompt: this.#messageChannel, options: sdkOptions });
|
|
1899
1982
|
this.#activeQueries.add(this.#persistentQuery);
|
|
1900
1983
|
this.#startBackgroundConsumer(callbacks);
|
|
1901
1984
|
}
|
|
@@ -1931,6 +2014,40 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1931
2014
|
session_id: this.#sessionId || '',
|
|
1932
2015
|
...(pushOpts?.priority && { priority: pushOpts.priority }),
|
|
1933
2016
|
};
|
|
2017
|
+
// Deferred auth restart: the subprocess was spawned under a fallback backend
|
|
2018
|
+
// that has since been replaced (Claude sign-in). Close it at this turn
|
|
2019
|
+
// boundary — only when idle, so a streaming turn is never aborted — and fall
|
|
2020
|
+
// through to the cold start, which resumes the same session (sdkOptions
|
|
2021
|
+
// carries resume: this.#sessionId) on the new env.
|
|
2022
|
+
if (this.#persistentQuery && this.#messageChannel && !this.#messageChannel.closed
|
|
2023
|
+
&& shouldRestartForAuth(this.#spawnAuthGen, authEnvGeneration, this.#turnsInFlight, !!this.#pendingInterrupt)) {
|
|
2024
|
+
console.log('🔑 Auth backend changed since spawn — restarting persistent session before this turn');
|
|
2025
|
+
this.closeSession();
|
|
2026
|
+
}
|
|
2027
|
+
// Session-switch backstop (#74): a resume target was armed for a DIFFERENT
|
|
2028
|
+
// session than the live query runs (not the id it was spawned for, not the
|
|
2029
|
+
// id init reported). Pushing would run this turn in the old session and
|
|
2030
|
+
// init would then report session_resume_failed {requested: armed, actual:
|
|
2031
|
+
// old} — the live bug. When idle, rebuild on the armed target (sdkOptions
|
|
2032
|
+
// already carries resume: armed, see run()). When busy, never abort the
|
|
2033
|
+
// old session's work: push as before and warn. A target the query was
|
|
2034
|
+
// already spawned for (a failed resume) is never retried — no loop.
|
|
2035
|
+
if (this.#persistentQuery && this.#messageChannel && !this.#messageChannel.closed) {
|
|
2036
|
+
const armed = this.#opts.resumeSessionId || null;
|
|
2037
|
+
if (armed && armed !== this.#spawnedResumeId && armed !== this.#sessionId) {
|
|
2038
|
+
const busy = this.busyState();
|
|
2039
|
+
if (busy.idle) {
|
|
2040
|
+
console.log(`🔀 Pending switch to ${armed.substring(0, 8)} — closing idle session ${this.#sessionId?.substring(0, 8) ?? '(new)'} and resuming the target`);
|
|
2041
|
+
this.closeSession();
|
|
2042
|
+
this.#sessionId = null;
|
|
2043
|
+
userMessage.session_id = '';
|
|
2044
|
+
}
|
|
2045
|
+
else {
|
|
2046
|
+
console.warn(`⚠️ Session switch to ${armed.substring(0, 8)} is pending but the live session is busy (${JSON.stringify(busy)}) — this turn still runs in ${this.#sessionId?.substring(0, 8) ?? 'the live session'}`);
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
this.#turnsInFlight++;
|
|
1934
2051
|
if (this.#persistentQuery && this.#messageChannel && !this.#messageChannel.closed) {
|
|
1935
2052
|
// Fast path — push to existing subprocess (no cold start).
|
|
1936
2053
|
// If an interrupt is in flight, order the push AFTER it settles: a message
|
|
@@ -1961,9 +2078,11 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1961
2078
|
}
|
|
1962
2079
|
// Cold start — create channel, push first message, start query + background consumer
|
|
1963
2080
|
console.log('🔄 Persistent session: cold start (first message, JSONL replay)');
|
|
2081
|
+
this.#spawnAuthGen = authEnvGeneration;
|
|
1964
2082
|
this.#messageChannel = new MessageChannel();
|
|
1965
2083
|
this.#messageChannel.push(userMessage);
|
|
1966
|
-
this.#
|
|
2084
|
+
this.#spawnedResumeId = sdkOptions?.resume ?? null;
|
|
2085
|
+
this.#persistentQuery = this.#queryFn({ prompt: this.#messageChannel, options: sdkOptions });
|
|
1967
2086
|
this.#activeQueries.add(this.#persistentQuery);
|
|
1968
2087
|
this.#startBackgroundConsumer(callbacks);
|
|
1969
2088
|
}
|
|
@@ -2102,6 +2221,8 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
2102
2221
|
// Result — marks end of a turn (but we keep consuming for next turn)
|
|
2103
2222
|
if (msg.type === 'result') {
|
|
2104
2223
|
logCacheUsage(msg.usage); // per-turn cache reads/writes (main loop only)
|
|
2224
|
+
if (this.#turnsInFlight > 0)
|
|
2225
|
+
this.#turnsInFlight--;
|
|
2105
2226
|
const turnMessageId = this.#currentTurnMessageId;
|
|
2106
2227
|
const turnChunks = [...this.#currentTurnChunks];
|
|
2107
2228
|
if (msg.result) {
|
|
@@ -2139,10 +2260,22 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
2139
2260
|
}
|
|
2140
2261
|
}
|
|
2141
2262
|
finally {
|
|
2142
|
-
this.#backgroundConsumerRunning = false;
|
|
2143
2263
|
this.#activeQueries.delete(pq);
|
|
2144
|
-
this
|
|
2145
|
-
this
|
|
2264
|
+
// Only tear down session fields this loop still owns. If closeSession() ran and a
|
|
2265
|
+
// newer query (+ consumer) was started before this stale loop drained, the fields
|
|
2266
|
+
// now belong to that newer query — nulling them would orphan its subprocess.
|
|
2267
|
+
if (this.#persistentQuery === pq) {
|
|
2268
|
+
this.#backgroundConsumerRunning = false;
|
|
2269
|
+
this.#persistentQuery = null;
|
|
2270
|
+
this.#messageChannel = null;
|
|
2271
|
+
// Turn-in-flight reset (#90 leak fix): this loop owned the subprocess and
|
|
2272
|
+
// it is now gone (iterator ended or errored), so no turn can still be
|
|
2273
|
+
// streaming on it. A turn that ended without a terminal `result` (an
|
|
2274
|
+
// interrupt or a mid-turn iterator error) never decremented #turnsInFlight;
|
|
2275
|
+
// leaving it > 0 would permanently block shouldRestartForAuth(). Strictly
|
|
2276
|
+
// safe — the subprocess is dead, so there is nothing in flight to miscount.
|
|
2277
|
+
this.#turnsInFlight = 0;
|
|
2278
|
+
}
|
|
2146
2279
|
console.log('🔒 Persistent session background consumer exited');
|
|
2147
2280
|
}
|
|
2148
2281
|
}
|
|
@@ -2327,7 +2460,11 @@ class ClaudeLLMStream extends llm.LLMStream {
|
|
|
2327
2460
|
console.log('input,', input, 'input.file_path', filePath, 'agent_type', agentType);
|
|
2328
2461
|
console.log(`🔍 canUseTool: ${toolName} filePath="${filePath}" keys=${Object.keys(input || {}).join(',')}`);
|
|
2329
2462
|
console.log(`🔍 canUseTool _options keys=[${Object.keys(_options || {}).join(', ')}] title="${_options?.title || ''}" decisionReason="${_options?.decisionReason || ''}" blockedPath="${_options?.blockedPath || ''}"`);
|
|
2330
|
-
if (
|
|
2463
|
+
if (isSafeArtifactPath(filePath)) {
|
|
2464
|
+
// Robust resolve+root check (not a substring): `..` traversal can no
|
|
2465
|
+
// longer trick the workspace auto-approve into clearing a write that
|
|
2466
|
+
// lands outside the session workspace. Legit absolute workspace
|
|
2467
|
+
// writes (~/.claude/projects/<slug>/osb/…) still auto-approve.
|
|
2331
2468
|
// Block writes to spec.md — the fast brain manages it
|
|
2332
2469
|
const fileName = filePath.split('/').pop() || '';
|
|
2333
2470
|
if (fileName === 'spec.md') {
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* Gated (state-changing or leaks session/process ids):
|
|
15
15
|
* user_text, claude_auth_code, permission_response, list_sessions,
|
|
16
16
|
* resume_session, continue_session, switch_session, session_selected,
|
|
17
|
+
* cancel_session_switch,
|
|
17
18
|
* mcp_toggle, set_agents, skill_add, skill_remove, noise_cancel,
|
|
18
19
|
* gate_send_anyway, stop_dispatch, join_meeting, leave_meeting,
|
|
19
20
|
* mute_participant, start_ide, stop_ide, spawn_background_session,
|
package/dist/data-sender-auth.js
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* Gated (state-changing or leaks session/process ids):
|
|
15
15
|
* user_text, claude_auth_code, permission_response, list_sessions,
|
|
16
16
|
* resume_session, continue_session, switch_session, session_selected,
|
|
17
|
+
* cancel_session_switch,
|
|
17
18
|
* mcp_toggle, set_agents, skill_add, skill_remove, noise_cancel,
|
|
18
19
|
* gate_send_anyway, stop_dispatch, join_meeting, leave_meeting,
|
|
19
20
|
* mute_participant, start_ide, stop_ide, spawn_background_session,
|
|
@@ -39,11 +40,14 @@
|
|
|
39
40
|
export const CONTROL_MESSAGE_TYPES = new Set([
|
|
40
41
|
'user_text',
|
|
41
42
|
'claude_auth_code',
|
|
43
|
+
'claude_auth_start',
|
|
42
44
|
'permission_response',
|
|
43
45
|
'list_sessions',
|
|
44
46
|
'resume_session',
|
|
45
47
|
'continue_session',
|
|
46
48
|
'switch_session',
|
|
49
|
+
// Cancels a deferred switch (#74) — state-changing, controller-only.
|
|
50
|
+
'cancel_session_switch',
|
|
47
51
|
'session_selected',
|
|
48
52
|
'mcp_toggle',
|
|
49
53
|
'set_agents',
|
package/dist/duck.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare const DUCK_LEVEL = 0.35;
|
|
2
|
+
/** Returns a NEW array with gain ramped linearly from `from` to `to`. Identity (same ref) at 1→1. */
|
|
3
|
+
export declare function applyGain(src: Int16Array, from: number, to: number): Int16Array;
|
|
4
|
+
export interface DuckController {
|
|
5
|
+
setDuck(target: number, reason?: string): void;
|
|
6
|
+
readonly target: number;
|
|
7
|
+
}
|
|
8
|
+
export declare function installDuck(session: any): DuckController | null;
|
package/dist/duck.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Native barge-in duck: lowers the agent's outgoing TTS volume while the user
|
|
2
|
+
// talks over it. @livekit/agents has no volume API on AudioOutput, so we wrap
|
|
3
|
+
// captureFrame on the outermost session.output.audio and scale Int16 samples.
|
|
4
|
+
// Frames already queued in the rtc AudioSource (~200ms) play at the old gain.
|
|
5
|
+
// Gain while ducked: 0.35 = 35% of original volume (65% quieter).
|
|
6
|
+
export const DUCK_LEVEL = 0.35;
|
|
7
|
+
/** Returns a NEW array with gain ramped linearly from `from` to `to`. Identity (same ref) at 1→1. */
|
|
8
|
+
export function applyGain(src, from, to) {
|
|
9
|
+
if (from === 1 && to === 1)
|
|
10
|
+
return src;
|
|
11
|
+
const n = src.length;
|
|
12
|
+
const dst = new Int16Array(n);
|
|
13
|
+
const step = n > 1 ? (to - from) / (n - 1) : 0;
|
|
14
|
+
for (let i = 0; i < n; i++) {
|
|
15
|
+
const g = n > 1 ? from + step * i : to;
|
|
16
|
+
let v = Math.round(src[i] * g);
|
|
17
|
+
if (v > 32767)
|
|
18
|
+
v = 32767;
|
|
19
|
+
else if (v < -32768)
|
|
20
|
+
v = -32768;
|
|
21
|
+
dst[i] = v;
|
|
22
|
+
}
|
|
23
|
+
return dst;
|
|
24
|
+
}
|
|
25
|
+
export function installDuck(session) {
|
|
26
|
+
const out = session?.output?.audio;
|
|
27
|
+
if (!out)
|
|
28
|
+
return null;
|
|
29
|
+
if (out.__duck)
|
|
30
|
+
return out.__duck;
|
|
31
|
+
const st = { gain: 1, target: 1 };
|
|
32
|
+
const orig = out.captureFrame.bind(out);
|
|
33
|
+
out.captureFrame = (frame) => {
|
|
34
|
+
if (st.gain === 1 && st.target === 1)
|
|
35
|
+
return orig(frame);
|
|
36
|
+
let next;
|
|
37
|
+
try {
|
|
38
|
+
const dst = applyGain(frame.data, st.gain, st.target);
|
|
39
|
+
next = new frame.constructor(dst, frame.sampleRate, frame.channels, frame.samplesPerChannel, frame.userdata);
|
|
40
|
+
st.gain = st.target;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return orig(frame);
|
|
44
|
+
}
|
|
45
|
+
return orig(next);
|
|
46
|
+
};
|
|
47
|
+
const ctrl = {
|
|
48
|
+
setDuck(target, reason) {
|
|
49
|
+
if (target === st.target)
|
|
50
|
+
return;
|
|
51
|
+
st.target = target;
|
|
52
|
+
console.log(`🦆 [duck] → ${target}${reason ? ` (${reason})` : ''}`);
|
|
53
|
+
},
|
|
54
|
+
get target() { return st.target; },
|
|
55
|
+
};
|
|
56
|
+
out.__duck = ctrl;
|
|
57
|
+
console.log(`🦆 [duck] installed on ${out.constructor?.name}`);
|
|
58
|
+
return ctrl;
|
|
59
|
+
}
|