Download runtime/src/body-core.js from cdismus4/chimera-jev-full-duplex: direct link, hf CLI and curl.
- Browser
- Download file 36.4 kB
-
https://huggingface.co/cdismus4/chimera-jev-full-duplex/resolve/main/runtime/src/body-core.js
- Command line
-
hf download hf://cdismus4/chimera-jev-full-duplex/runtime/src/body-core.js
-
curl -L -o body-core.js https://huggingface.co/cdismus4/chimera-jev-full-duplex/resolve/main/runtime/src/body-core.js
36.4 kB
| // 体の配線(Base v1 公開面のみ): | |
| // マイク(24kHz) → 耳 W=4 → 反射 ep17 → 語彙選択/意図スロット → ドライバ v1 → CHIMERA 口 | |
| // 規則は配線契約(Stage 2 設計 §3+搭載仕様 §6/§7)と推奨設定(W=4+発話ガード)に従う。 | |
| // 切り出し元:Phase 3 ゲーム src/body.js(正本)。ゲーム側の脳・ASR は含まない | |
| // (意図は intent-slot.js の公開面からホストが渡す。README の「境界」を参照)。 | |
| import { ChimeraPlanner, buildSpeech, createMouthEngine, createMouthPlayer } from './mouth.js'; | |
| import { IntentSlot } from './intent-slot.js'; | |
| export const ACTIONS = ['SILENT_LISTEN', 'BACKCHANNEL', 'TAKE_TURN', 'CONTINUE', 'YIELD', 'NONVERBAL_EXPRESS']; | |
| const BC_GUARD_MS = 2000; // 発話ガード:相槌の 2 秒抑止(ベンチ層 (4)) | |
| const BUSY_MIN_MS = 480; // 発話ブロックの下限(ベンチ busyUntilMs、層 (2)) | |
| const TURN_SILENCE_TICKS = 10; // turnHasSpoken 解除までの SILENCE 連続ティック数(ベンチ層 (3)、800ms) | |
| // 意図配送ポリシー(v0.11 で種別分け、v0.12 で保険を作り替え):状況意図は | |
| // バーク(発話ゲートのみで即時配送)、返事意図はターン経路が本命で、床開き | |
| // トリガの保険を併設する(tick 内の各所を参照)。 | |
| const REPLY_FALLBACK_WAIT_MS = 350; // 返事意図の保険待機(ASR確定時点でVAD+解読約1秒経過済み+裏プリレンダー並列化で体感ラグを短縮) | |
| const REPLY_FALLBACK_SILENCE_TICKS = 4; // 保険の静寂条件:現ティックより前の SILENT_LISTEN 連続ティック数(320ms) | |
| const SPEECH_CACHE_MAX = 32; // 発話 PCM+声道フレームの LRU キャッシュ上限件数 | |
| const EAR_WIN = 7680; // W=4 = 320ms @24kHz | |
| const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v)); | |
| const round4 = v => Math.round(v * 10000) / 10000; | |
| // ---------- ORT 読み込み(.mjs は Blob 経由、wasm は wasmBinary で渡す:配信 MIME の罠回避) ---------- | |
| export async function loadOrt(baseUrl) { | |
| const mjsText = await (await fetch(baseUrl + 'ort.wasm.bundle.min.mjs')).text(); | |
| const blob = new Blob([mjsText], { type: 'text/javascript' }); | |
| const ort = await import(URL.createObjectURL(blob)); | |
| ort.env.wasm.numThreads = 1; | |
| ort.env.wasm.wasmBinary = await (await fetch(baseUrl + 'ort-wasm-simd-threaded.wasm')).arrayBuffer(); | |
| return ort; | |
| } | |
| export async function fetchBytes(url) { | |
| const res = await fetch(url); | |
| // HTTP エラーの本文(404 の HTML 等)をバイナリと誤読させない | |
| if (!res.ok) throw new Error(`fetchBytes: HTTP ${res.status} (${url})`); | |
| return new Uint8Array(await res.arrayBuffer()); | |
| } | |
| // 大きなファイル用:逐次読み込み+進捗通知+サイズ検証+リトライ(最大3回)。 | |
| // 途中切断は Content-Length との突き合わせで検出し、最初から取り直す。 | |
| export async function fetchBytesRobust(url, { log = () => {}, onProgress = null, label = url, tries = 3 } = {}) { | |
| let lastErr = null; | |
| for (let attempt = 1; attempt <= tries; attempt++) { | |
| try { | |
| const res = await fetch(url); | |
| if (!res.ok) throw new Error(`HTTP ${res.status}`); | |
| const total = Number(res.headers.get('Content-Length')) || 0; | |
| let buf; | |
| let lastPct = -1; | |
| if (res.body && typeof res.body.getReader === 'function') { | |
| const reader = res.body.getReader(); | |
| const chunks = []; | |
| let got = 0; | |
| for (;;) { | |
| const { done, value } = await reader.read(); | |
| if (done) break; | |
| chunks.push(value); got += value.byteLength; | |
| if (onProgress && total > 0) { | |
| const pct = Math.floor((got / total) * 100); | |
| if (pct >= lastPct + 10) { lastPct = pct; onProgress(got, total, pct); } | |
| } | |
| } | |
| buf = new Uint8Array(got); | |
| let off = 0; | |
| for (const c of chunks) { buf.set(c, off); off += c.byteLength; } | |
| } else { | |
| buf = new Uint8Array(await res.arrayBuffer()); | |
| } | |
| if (total > 0 && buf.byteLength !== total) { | |
| throw new Error(`サイズ不一致: ${buf.byteLength} / ${total} bytes(途中切断の疑い)`); | |
| } | |
| if (onProgress && total > 0 && lastPct < 100) { | |
| onProgress(total, total, 100); | |
| } | |
| return buf; | |
| } catch (e) { | |
| lastErr = e; | |
| log(`取得リトライ ${attempt}/${tries}: ${label} — ${e.message}`); | |
| } | |
| } | |
| throw lastErr || new Error(`取得に失敗: ${label}`); | |
| } | |
| // ---------- かな → モーラ列(配線の責務:ꜜ と ? を除去してから最長一致で分割) ---------- | |
| export function makeMoraSplitter(tables) { | |
| const keys = Object.keys(tables.mora).sort((a, b) => b.length - a.length); | |
| return (kana) => { | |
| const s = kana.replace(/ꜜ|\?|、|。| /g, ''); | |
| // 仕様(integration-spec §3.2):文頭に「ー」は置けない。長音はドライバ前処理で | |
| // 「直前節の繰り返し」として扱われるため、先頭にあると参照先が無く落ちる。弾く。 | |
| if (s.startsWith('ー')) return null; | |
| const out = []; | |
| let i = 0; | |
| while (i < s.length) { | |
| const k = keys.find(k => s.startsWith(k, i)); | |
| if (!k) return null; | |
| out.push(k); i += k.length; | |
| } | |
| return out; | |
| }; | |
| } | |
| // ---------- ドライバ前処理(搭載仕様 §3) ---------- | |
| export function buildDriverInputs(tables, morae) { | |
| const M = morae.length; | |
| const segs = [], counts = []; | |
| for (const m of morae) { | |
| const ss = tables.mora[m].segments; | |
| if (ss.length === 0 && segs.length === 0) { counts.push(0); } // 文頭の長音:参照先が無いので節を生やさない(通常は分割側で棄却済み) | |
| else if (ss.length === 0) { segs.push(segs[segs.length - 1]); counts.push(1); } // 長音「ー」:直前節を繰り返す | |
| else { for (const s of ss) segs.push(s); counts.push(ss.length); } | |
| } | |
| const S = segs.length; | |
| const segMora = [], pos = []; | |
| counts.forEach((c, mi) => { for (let j = 0; j < c; j++) { segMora.push(mi); pos.push(j); } }); | |
| const segFeat = new Float32Array(S * 6); | |
| for (let j = 0; j < S; j++) { | |
| const c = counts[segMora[j]]; | |
| segFeat[j * 6 + 0] = c > 1 ? pos[j] / (c - 1) : 0; | |
| segFeat[j * 6 + 1] = pos[j] === 0 ? 1 : 0; | |
| segFeat[j * 6 + 2] = pos[j] === c - 1 ? 1 : 0; | |
| segFeat[j * 6 + 3] = segMora[j] === M - 1 ? 1 : 0; | |
| segFeat[j * 6 + 4] = j / Math.max(S - 1, 1); | |
| segFeat[j * 6 + 5] = M > 1 ? segMora[j] / (M - 1) : 0; | |
| } | |
| return { | |
| moraIds: morae.map(m => tables.mora[m].id), | |
| segMora, segPhoneme: segs.map(([, pip]) => tables.phoneme_to_id[pip]), | |
| segFeat, segs, | |
| }; | |
| } | |
| // ---------- ドライバ後処理(搭載仕様 §4) ---------- | |
| export function planFromDriver(tables, segs, ovData, logDurData) { | |
| const keys19 = tables.keys19; | |
| return segs.map(([rip, pip], j) => { | |
| const seg = { ipa: rip, dur: round4(clamp(Math.exp(logDurData[j]), 0.03, 0.35)) }; | |
| const spec = tables.spec_keys[pip] || []; | |
| if (spec.length) { | |
| const ov = {}; | |
| for (const key of spec) { | |
| const [lo, hi] = tables.bounds19[key]; | |
| ov[key] = round4(clamp(ovData[j * 19 + keys19.indexOf(key)], lo, hi)); | |
| } | |
| seg.overrides = ov; | |
| } | |
| return seg; | |
| }); | |
| } | |
| // ---------- 語彙選択(query を L2 正規化し role マスク内で cos 最大。ゼロ query は role 先頭) ---------- | |
| // opts.bias:{ entryId: 重み }(ホストのパレット)。opts.recent:{ entryId: 0..1 }(直近使用度)。 | |
| // スコア = cos + BC_BIAS_SCALE × パレット重み − BC_RECENT_PENALTY × 直近使用度。 | |
| // バイアス等の指定が無い呼び出しは従来どおりの cos 最大(ゼロ query は先頭)。 | |
| const BC_BIAS_SCALE = 0.15; | |
| const BC_RECENT_PENALTY = 0.12; | |
| const BC_RECENT_WINDOW_MS = 30000; // 直近使用減点が効く窓(この間隔で 1→0 に減衰) | |
| export function selectEntry(bank, role, query, opts = {}) { | |
| const entries = bank.entries.filter(e => e.role === role); | |
| if (!entries.length) return null; | |
| const bias = opts.bias || null; | |
| const recent = opts.recent || null; | |
| let normSq = 0; | |
| for (let i = 0; i < 128; i++) normSq += query[i] * query[i]; | |
| if (!(normSq > 1e-12) && !bias && !recent) return entries[0]; | |
| const norm = normSq > 1e-12 ? Math.sqrt(normSq) : 0; | |
| const biasScale = opts.biasScale ?? BC_BIAS_SCALE; | |
| const recentPenalty = opts.recentPenalty ?? BC_RECENT_PENALTY; | |
| let best = entries[0], bestDot = -Infinity; | |
| for (const e of entries) { | |
| let d = 0; | |
| if (norm > 0) { for (let i = 0; i < 128; i++) d += (query[i] / norm) * e.vec[i]; } | |
| if (bias) d += biasScale * (bias[e.id] || 0); | |
| if (recent) d -= recentPenalty * (recent[e.id] || 0); | |
| if (d > bestDot) { bestDot = d; best = e; } | |
| } | |
| return best; | |
| } | |
| // ---------- 体のコア(80ms ティック) ---------- | |
| export class BodyCore { | |
| constructor({ ort, earSess, reflexSess, driverSess, runTick = null, runDriver = null, tables, bank, planner, speakOut, prepareOut = null, playOut = null, log, onUtterance }) { | |
| this.ort = ort; this.earSess = earSess; this.reflexSess = reflexSess; this.driverSess = driverSess; | |
| this.runTick = runTick; | |
| this.runDriver = runDriver; | |
| this.tables = tables; this.bank = bank; this.planner = planner; | |
| this.speakOut = speakOut; | |
| this.prepareOut = prepareOut; | |
| this.playOut = playOut; | |
| this.log = log; this.onUtterance = onUtterance || (() => {}); | |
| this.splitMora = makeMoraSplitter(tables); | |
| this.intents = new IntentSlot(log); | |
| this.paletteProvider = null; // ホストの相槌パレット供給口(任意):(now) => { entryId: 重み } | null | |
| this.speechCache = new Map(); | |
| this.speechInFlight = new Map(); | |
| this.state = new Float32Array(4 * 384); | |
| this.zState = new Float32Array(8); | |
| this.selfEff = new Float32Array(24); // 2 ティック(160ms)遅延で供給する(tick 内の 2 段シフト参照) | |
| this.pendingEff = new Float32Array(24); | |
| this.speakEndAt = 0; // performance.now 基準 | |
| this.busyUntil = 0; // 発話ブロック解除時刻(ベンチ busyUntilMs、層 (2)) | |
| this.ownVoiceIntervals = []; // 自声区間 {start, end, kind}(performance.now 基準。ホスト側 ASR の自声除外用に公開。kind は 'bc'=相槌/'main'=それ以外) | |
| this._busyActive = false; // 発話ブロックのログ遷移用 | |
| this.turnHasSpoken = false; // 発話後、SILENCE 10 連続まで CONTINUE 抑止(ベンチ層 (3)) | |
| this.silenceStreak = 0; // SILENT_LISTEN の連続ティック数 | |
| this.lastBcAt = -1e9; | |
| this.bcRecent = []; // BACKCHANNEL の使用履歴 { id, at }(直近使用減点用) | |
| this.lastTurnAt = -1e9; // 直近の TAKE_TURN 判定時刻(ターンラッチ用) | |
| this.turnCredit = false; // 保持(発話中/発話ブロック)中に TAKE_TURN が立った記録(意図配送用) | |
| this.diagTicks = 0; // 耳診断の集計ティック数 | |
| this.diagMicMax = 0; // 耳診断:区間のマイク RMS 最大 | |
| this.diagBcMax = 0; // 耳診断:区間の相槌確率最大 | |
| this.ownRms = 0; | |
| this.stats = { ticks: 0, bcSuppressed: 0, speakSuppressed: 0, busySuppressed: 0, contSuppressed: 0, utterances: 0, byAction: {} }; | |
| this.timing = { ear: 0, reflex: 0, driver: 0, n: 0 }; | |
| } | |
| // 意図の公開面:ホストが「次に言わせたい一文」を預ける(intent-slot.js)。 | |
| // 預けられたら、口のプリレンダーがある構成では裏で合成を先行する。 | |
| // now は任意:tick(wavWindow, now) を自分の時計で回すホストは、同じ now を | |
| // 渡すことで意図のセット時刻をティックの時計に揃えられる。省略時は | |
| // performance.now()(tick の now と同じ時計系が前提)。 | |
| setIntent(desc, now = performance.now()) { | |
| const ok = this.intents.set(desc, now); | |
| if (ok && this.intents.intent) this.prefetchIntent(this.intents.intent); | |
| return ok; | |
| } | |
| // 状況意図の簡便口(phrase: { text, show?, rateMul?, pitchOffsetHz?, ttlMs? }) | |
| setSituationIntent(tag, phrase) { | |
| return this.setIntent({ ...phrase, kind: 'situation', tag }); | |
| } | |
| // 相槌パレットの供給口(任意):fn(now) が { entryId: 重み } を返すと、 | |
| // BACKCHANNEL の語彙選択で僅差の競合にだけ効く(タイミングは反射が握る)。 | |
| setPaletteProvider(fn) { this.paletteProvider = fn; } | |
| // 相槌パレット(ホスト供給)と直近使用減点(ここ)を効かせた BACKCHANNEL 選択 | |
| selectBcEntry(query, now) { | |
| const bias = this.paletteProvider ? this.paletteProvider(now) : null; | |
| let recent = null; | |
| for (const r of this.bcRecent) { | |
| const age = now - r.at; | |
| if (age >= 0 && age < BC_RECENT_WINDOW_MS) { | |
| if (!recent) recent = {}; | |
| recent[r.id] = Math.max(recent[r.id] || 0, 1 - age / BC_RECENT_WINDOW_MS); | |
| } | |
| } | |
| return selectEntry(this.bank, 'BACKCHANNEL', query, { bias, recent }); | |
| } | |
| noteBcUsed(id, now) { | |
| this.bcRecent.push({ id, at: now }); | |
| if (this.bcRecent.length > 10) this.bcRecent.splice(0, this.bcRecent.length - 10); | |
| } | |
| noteOwnVoice(rms, speaking, now) { | |
| this.pendingEff[0] = clamp(rms, 0, 1); | |
| this.pendingEff[1] = speaking ? 1 : 0; | |
| } | |
| // 発話中かは実時刻で判定する。speakEndAt は発話開始の実時刻+実尺で記録する | |
| // ため、tick の now(ティック開始時刻)では判定できない。ここは | |
| // performance.now() が正で、引数 now には揃えられない。 | |
| get speaking() { return performance.now() < this.speakEndAt; } | |
| async synthesizeMorae(morae, rateMul, pitchOffsetHz) { | |
| const f0 = clamp(120 + pitchOffsetHz, 100, 140); | |
| const rate = 1.15 * rateMul; | |
| const cacheKey = `${morae.join(' ')}|${rate.toFixed(3)}|${Math.round(f0)}`; | |
| if (this.prepareOut) { | |
| const cached = this.speechCache.get(cacheKey); | |
| if (cached) { | |
| this.speechCache.delete(cacheKey); | |
| this.speechCache.set(cacheKey, cached); | |
| return { f0, rendered: cached, cacheHit: true }; | |
| } | |
| const inflight = this.speechInFlight.get(cacheKey); | |
| if (inflight) { | |
| const rendered = await inflight; | |
| return { f0, rendered, cacheHit: false }; | |
| } | |
| } | |
| const buildJob = async () => { | |
| const inp = buildDriverInputs(this.tables, morae); | |
| const ps = this.tables.prosody_stats; | |
| const pros = new Float32Array([(Math.log(f0) - ps.logf0_mean) / ps.logf0_std, (Math.log(rate) - ps.lograte_mean) / ps.lograte_std]); | |
| const bi = a => BigInt64Array.from(a, v => BigInt(v)); | |
| // 所要時間の実測は実時計で行う(tick の now はホスト都合の論理時計であり | |
| // うるため、実測に混ぜない)。以下の tick 内メインスレッド推論の計時も同じ。 | |
| const t0 = performance.now(); | |
| let ovData, logDurData; | |
| if (this.runDriver) { | |
| const res = await this.runDriver({ | |
| moraIds: bi(inp.moraIds), | |
| segMora: bi(inp.segMora), | |
| segPhoneme: bi(inp.segPhoneme), | |
| segFeat: inp.segFeat, | |
| nSegs: inp.segs.length, | |
| pros, | |
| }); | |
| ovData = res.ov; | |
| logDurData = res.logDur; | |
| } else { | |
| const feeds = { | |
| mora_ids: new this.ort.Tensor('int64', bi(inp.moraIds), [1, inp.moraIds.length]), | |
| seg_mora: new this.ort.Tensor('int64', bi(inp.segMora), [1, inp.segMora.length]), | |
| seg_phoneme: new this.ort.Tensor('int64', bi(inp.segPhoneme), [1, inp.segPhoneme.length]), | |
| seg_feat: new this.ort.Tensor('float32', inp.segFeat, [1, inp.segs.length, 6]), | |
| pros: new this.ort.Tensor('float32', pros, [1, 2]), | |
| }; | |
| let out = null; | |
| try { | |
| out = await this.driverSess.run(feeds); | |
| ovData = new Float32Array(out.ov.data); | |
| logDurData = new Float32Array(out.log_dur.data); | |
| } finally { | |
| for (const t of Object.values(feeds)) if (t && typeof t.dispose === 'function') { try { t.dispose(); } catch {} } | |
| if (out) for (const t of Object.values(out)) if (t && typeof t.dispose === 'function') { try { t.dispose(); } catch {} } | |
| } | |
| } | |
| this.timing.driver += performance.now() - t0; this.timing.n++; | |
| const segments = planFromDriver(this.tables, inp.segs, ovData, logDurData); | |
| const speech = buildSpeech(this.planner, segments, f0); | |
| if (!this.prepareOut) return { speech }; | |
| const rendered = await this.prepareOut(speech.records, speech.count, f0, speech.end); | |
| this.speechCache.set(cacheKey, rendered); | |
| while (this.speechCache.size > SPEECH_CACHE_MAX) { | |
| const oldestKey = this.speechCache.keys().next().value; | |
| if (oldestKey === undefined) break; | |
| this.speechCache.delete(oldestKey); | |
| } | |
| return rendered; | |
| }; | |
| if (!this.prepareOut) { | |
| const { speech } = await buildJob(); | |
| return { f0, speech, rendered: null, cacheHit: false }; | |
| } | |
| const job = buildJob(); | |
| this.speechInFlight.set(cacheKey, job); | |
| try { | |
| const rendered = await job; | |
| return { f0, rendered, cacheHit: false }; | |
| } finally { | |
| if (this.speechInFlight.get(cacheKey) === job) this.speechInFlight.delete(cacheKey); | |
| } | |
| } | |
| prefetchIntent(intent) { | |
| if (!intent || !intent.text || !this.prepareOut) return; | |
| const morae = this.splitMora(intent.text); | |
| if (!morae) return; | |
| this.synthesizeMorae(morae, intent.rateMul ?? 1, intent.pitchOffsetHz ?? 0).catch(() => {}); | |
| } | |
| // 発話実行。kind: 自声区間に記録する発話の種類。'bc'=相槌(語彙経路の | |
| // BACKCHANNEL)、それ以外は全て 'main'(返事・バーク・合成ターン等)。 | |
| // ホスト側 ASR が「相槌との重なりは日常で事故ではない」と区別するための印。 | |
| async speakMorae(morae, rateMul, pitchOffsetHz, displayText, kind = 'main') { | |
| const syn = await this.synthesizeMorae(morae, rateMul, pitchOffsetHz); | |
| const playInfo = (this.prepareOut && this.playOut && syn.rendered) | |
| ? await this.playOut(syn.rendered, displayText) | |
| : await this.speakOut(syn.speech.records, syn.speech.count, syn.f0, displayText, syn.speech.end); | |
| const fallbackEnd = syn.speech ? syn.speech.end : (syn.rendered ? syn.rendered.durationSec : 0.4); | |
| const actualDurSec = (playInfo && typeof playInfo.durationSec === 'number') ? playInfo.durationSec : fallbackEnd; | |
| // 発話開始時刻は合成・再生開始を終えたこの時点の実時刻で取る。tick の now は | |
| // ティック開始時刻で、合成の所要時間だけ過去になるため使わない。 | |
| const playStartMs = performance.now(); | |
| this.speakEndAt = playStartMs + (actualDurSec + 0.15) * 1000; | |
| // ベンチ層 (2) 発話ブロック:busyUntil = 発話完了時刻 + max(480, 発話長ms + 120) | |
| const durMs = actualDurSec * 1000; | |
| const blockMs = Math.max(BUSY_MIN_MS, durMs + 120); | |
| this.busyUntil = playStartMs + durMs + blockMs; | |
| // ホスト側 ASR の自声除外用に、実際に音が出た区間のみ記録(無音時は記録しない) | |
| // 再生実尺 +80ms(speakEndAt の +150ms は発話状態フラグ用に維持し、ASR 除外帯の過剰膨張を抑える) | |
| if (!playInfo || playInfo.peakRms >= 0.002) { | |
| this.ownVoiceIntervals.push({ start: playStartMs, end: playStartMs + durMs + 80, kind }); | |
| if (this.ownVoiceIntervals.length > 40) this.ownVoiceIntervals.splice(0, this.ownVoiceIntervals.length - 40); | |
| } | |
| if (!this._busyActive) { | |
| this._busyActive = true; | |
| this.log(`自声ガード ON(+${Math.round(blockMs)}ms 間は連発を抑止)`); | |
| } | |
| // ベンチ層 (3) turnHasSpoken:発話したら立て、SILENCE 10 ティック連続で落とす(tick 側) | |
| if (!this.turnHasSpoken) { | |
| this.turnHasSpoken = true; | |
| this.log('turnHasSpoken ON(CONTINUE 抑止開始)'); | |
| } | |
| this.silenceStreak = 0; | |
| this.stats.utterances++; | |
| this.onUtterance(displayText, actualDurSec); | |
| return actualDurSec; | |
| } | |
| // wavWindow: 直近 7680 サンプル(24kHz)。now: performance.now() | |
| async tick(wavWindow, now) { | |
| this.stats.ticks++; | |
| // 意図の期限切れは毎ティック能動的に知らせる(ターンが来なかった意図の行方をログで追えるように) | |
| this.intents.expireIntent(now); | |
| // selfEff は 2 ティック(160ms)遅延で供給([0]=自声 RMS、[1]=発話フラグ、[2..23]=0)。 | |
| // selfEff/pendingEff の 2 段シフトレジスタのため、今ティックの観測が反射へ | |
| // 届くのは 2 ティック先になる。この遅延量は実機検証済みの正本(Phase 3 ゲーム)と | |
| // 同一の実装で、挙動は変えず記述だけを実態に合わせたもの。 | |
| const eff = this.selfEff; | |
| this.selfEff = this.pendingEff; | |
| this.pendingEff = new Float32Array(24); | |
| this.noteOwnVoice(this.ownRms, this.speaking, now); | |
| // ↑ pendingEff は次ティック用に今の観測を積む(noteOwnVoice が pendingEff を書く) | |
| let logits, queryVec; | |
| if (this.runTick) { | |
| const res = await this.runTick({ | |
| wav: wavWindow, | |
| eff, | |
| zState: this.zState, | |
| state: this.state, | |
| }); | |
| this.timing.ear += res.earMs; | |
| this.timing.reflex += res.reflexMs; | |
| this.state = res.stateOut; | |
| this.zState = res.zStateOut; | |
| logits = res.logits; | |
| queryVec = res.queryVec; | |
| } else { | |
| // 耳:W=4 窓を実行し最後のフレームを現在の earEmb とする(t+1 読み替えは系全体の 80ms 遅延として受容) | |
| // 計時は実測なので performance.now()(synthesizeMorae のコメント参照) | |
| let t0 = performance.now(); | |
| const earFeeds = { wav: new this.ort.Tensor('float32', wavWindow, [1, 1, EAR_WIN]) }; | |
| let earOut = null, reflexFeeds = null, out = null; | |
| try { | |
| earOut = await this.earSess.run(earFeeds); | |
| // 最終フレームを現在の earEmb とする(末尾から取るので W=8 の窓でも正しい) | |
| const emb = earOut.ear_emb.data.slice(earOut.ear_emb.data.length - 512); | |
| this.timing.ear += performance.now() - t0; | |
| t0 = performance.now(); | |
| reflexFeeds = { | |
| ear_emb: new this.ort.Tensor('float32', emb, [1, 512]), | |
| self_efference: new this.ort.Tensor('float32', eff, [1, 24]), | |
| z_state: new this.ort.Tensor('float32', this.zState, [1, 8]), | |
| state_in: new this.ort.Tensor('float32', this.state, [1, 4, 384]), | |
| }; | |
| out = await this.reflexSess.run(reflexFeeds); | |
| this.timing.reflex += performance.now() - t0; | |
| this.state = out.state_out.data.slice(); | |
| this.zState = out.z_state_next.data.slice(); | |
| logits = out.action_logits.data.slice(); | |
| queryVec = out.query_vec.data.slice(); | |
| } finally { | |
| for (const t of Object.values(earFeeds)) if (t && typeof t.dispose === 'function') { try { t.dispose(); } catch {} } | |
| if (earOut) for (const t of Object.values(earOut)) if (t && typeof t.dispose === 'function') { try { t.dispose(); } catch {} } | |
| if (reflexFeeds) for (const t of Object.values(reflexFeeds)) if (t && typeof t.dispose === 'function') { try { t.dispose(); } catch {} } | |
| if (out) for (const t of Object.values(out)) if (t && typeof t.dispose === 'function') { try { t.dispose(); } catch {} } | |
| } | |
| } | |
| let action = 0; | |
| for (let i = 1; i < 6; i++) if (logits[i] > logits[action]) action = i; | |
| const name = ACTIONS[action]; | |
| this.stats.byAction[name] = (this.stats.byAction[name] || 0) + 1; | |
| if (name === 'TAKE_TURN') this.lastTurnAt = now; | |
| // 耳診断(実機での目視確認用):直近約2秒(25ティック)のマイク RMS(最新80ms分)と | |
| // 反射の相槌確率の最大値を集計し、2秒に1行だけログへ出す。ベンチ実測では、人の声の | |
| // 区間では相槌確率が 1.00 近くまで上がり、物音・ノイズでは 0.35 以下に留まる。 | |
| // 読み方:話しかけると確率が上がり、机を叩く等の物音では上がらなければ耳は働いている。 | |
| { | |
| let mx = -Infinity; | |
| for (let i = 0; i < 6; i++) if (logits[i] > mx) mx = logits[i]; | |
| let sum = 0, bcExp = 0; | |
| for (let i = 0; i < 6; i++) { const e = Math.exp(logits[i] - mx); if (i === 1) bcExp = e; sum += e; } | |
| const bcProb = bcExp / sum; | |
| let sq = 0; | |
| const seg = wavWindow.subarray(wavWindow.length - 1920); | |
| for (let i = 0; i < seg.length; i++) sq += seg[i] * seg[i]; | |
| const micRms = Math.sqrt(sq / Math.max(1, seg.length)); | |
| if (micRms > this.diagMicMax) this.diagMicMax = micRms; | |
| if (bcProb > this.diagBcMax) this.diagBcMax = bcProb; | |
| if (++this.diagTicks >= 25) { | |
| this.log(`耳診断: 直近2秒 マイクRMS最大 ${this.diagMicMax.toFixed(3)} / 相槌確率最大 ${this.diagBcMax.toFixed(2)}`); | |
| this.diagTicks = 0; this.diagMicMax = 0; this.diagBcMax = 0; | |
| } | |
| } | |
| // turnHasSpoken(ベンチ層 (3))の解除判定:argmax の記録は抑止中も続け、 | |
| // SILENT_LISTEN が 10 ティック連続したらフラグを落とす。 | |
| // silenceStreakBefore はこのティックの argmax を反映する前の連続数(返事意図の | |
| // 保険配送の静寂条件が「直前まで静かだったか」を見るために使う)。 | |
| const silenceStreakBefore = this.silenceStreak; | |
| if (name === 'SILENT_LISTEN') { | |
| this.silenceStreak++; | |
| if (this.turnHasSpoken && this.silenceStreak >= TURN_SILENCE_TICKS) { | |
| this.turnHasSpoken = false; | |
| this.log('turnHasSpoken OFF(SILENCE 10 ティック連続)'); | |
| } | |
| } else { | |
| this.silenceStreak = 0; | |
| } | |
| if (this.speaking) { | |
| if (name === 'TAKE_TURN') this.turnCredit = true; // 保持中に反射がターンを要求した記録(配送可能になった最初のティックで意図に使う) | |
| if (name === 'SILENT_LISTEN') return { action: name }; | |
| this.stats.speakSuppressed++; | |
| return { action: name, held: 'speaking' }; | |
| } | |
| // 発話ブロック(ベンチ層 (2)):busyUntil までは新規発話(相槌の発話実行・TAKE_TURN・ | |
| // ターンラッチ経由の意図発話を含む)を抑止する。ここでは意図を消費しない | |
| // (takeForTurn を呼ばない)ので、意図は TTL の範囲で保持される。 | |
| if (this._busyActive && now >= this.busyUntil) { | |
| this._busyActive = false; | |
| this.log('自声ガード OFF'); | |
| } | |
| if (now < this.busyUntil) { | |
| if (name === 'TAKE_TURN') this.turnCredit = true; // 発話ブロック中に立ったターン要求もクレジットに残す | |
| if (name !== 'SILENT_LISTEN') { | |
| this.stats.busySuppressed++; | |
| return { action: name, held: 'busy' }; | |
| } | |
| return { action: name }; | |
| } | |
| // バーク配送(v0.11):状況意図(departure/near_miss 等のイベント反応)は会話の | |
| // ターンを待たない。ここに到達した時点で発話中ではなく、now >= busyUntil なら | |
| // 発話ブロック中でもない(上の保持分岐を参照)。その最初の発話可能ティックで、 | |
| // 反射の argmax が何であっても即時に配送する。根拠:v0.10 実機では反射の | |
| // TAKE_TURN が一度も発火せず(ターンは相手の声が終わって間が空く時に生まれる | |
| // ため、無言+テキスト入力の条件では床が開かない)、状況意図が全て期限切れに | |
| // なった。イベント反応は鮮度が命なので、ゲート(発話中でない+発話ブロック | |
| // 中でない)だけを通す。発話したら溜まっていたターン要求(クレジット)は | |
| // この発話で消費されたものとして落とす。 | |
| if (this.intents.intent && this.intents.intent.kind === 'situation' && now >= this.busyUntil) { | |
| // quietOnly の状況意図(ゲームの被り修復が該当)だけは追加条件:その言葉は | |
| // 「誰も喋っていない」瞬間に届けるものなので、プレイヤーがまだ喋っている | |
| // (argmax が SILENT_LISTEN でない)ティックでは踏まず、意図を保持したまま | |
| // 通常処理へ流す。 | |
| const needsQuiet = this.intents.intent.quietOnly && name !== 'SILENT_LISTEN'; | |
| if (!needsQuiet) { | |
| const intent = this.intents.takeForTurn(now); | |
| if (intent) { | |
| const morae = this.splitMora(intent.text); | |
| if (morae) { | |
| this.turnCredit = false; | |
| this.log(`意図: [${intent.tag}] をバーク即時で発話`); | |
| await this.speakMorae(morae, intent.rateMul, intent.pitchOffsetHz, intent.show || intent.text); | |
| return { action: 'BARK', said: intent.text, via: 'intent', route: 'bark' }; | |
| } | |
| this.log(`意図: [${intent.tag}] のモーラ分割に失敗したため破棄`); | |
| } | |
| } | |
| } | |
| // ターンラッチ+ターンクレジット:TAKE_TURN の argmax は自発話の最中に出ることが多い | |
| // (実機トレースでも同型で、その多くは発話終了と同時に消える)。発話が終わった直後 | |
| // (600ms 以内)に意図が待っている場合、そのターン判定を有効として意図フレーズを | |
| // 発話する(ラッチ)。反射の許可をホストが上書きするのではなく、反射の判定の有効期限を | |
| // アダプタ側で短く保持する扱い(設計メモ §5.1 のアダプタ責務の範囲)。 | |
| // ただし 600ms ラッチだけでは、発話ブロック(発話完了後も最低 480ms 続く)の陰で | |
| // 立ったターン要求が失効し、意図が飢餓することがあった(v0.9 実機で確認:意図は | |
| // セットされるが発話は全て反射の相槌・継続語だった)。そこで、保持(発話中/発話 | |
| // ブロック)中に TAKE_TURN が立った場合はクレジットとして覚え、最初に発話可能に | |
| // なったティックで意図の配送に使う。クレジットはそのティックで失効するので、 | |
| // 反射がターンを取っていない瞬間に意図を押し込むことはない(タイミング主権は反射側)。 | |
| // v0.11 以降、この経路が受け持つのは返事意図のみ(状況意図は上のバークが先に取る。 | |
| // 発話ブロック中の SILENT ティックでラッチが状況意図をゲートの外から配送する | |
| // ことも、種別で分けたことで無くなった)。 | |
| const credit = this.turnCredit; | |
| this.turnCredit = false; | |
| if (this.intents.intent && this.intents.intent.kind === 'reply' && (now - this.lastTurnAt <= 600 || credit)) { | |
| const intent = this.intents.takeForTurn(now); | |
| if (intent) { | |
| const morae = this.splitMora(intent.text); | |
| if (morae) { | |
| if (credit && now - this.lastTurnAt > 600) this.log('意図: 保持中に溜まったターン要求(クレジット)で意図を発話'); | |
| this.log(`意図: [${intent.tag}] をターン経路(${credit ? 'クレジット' : 'ラッチ'})で発話`); | |
| await this.speakMorae(morae, intent.rateMul, intent.pitchOffsetHz, intent.show || intent.text); | |
| return { action: 'TAKE_TURN(latch)', said: intent.text, via: 'intent', route: 'turn' }; | |
| } | |
| this.log(`意図: [${intent.tag}] のモーラ分割に失敗したため破棄`); | |
| } | |
| } | |
| // 保険配送(v0.12、床開きトリガ):返事意図がターン経路で届かないまま待たされた | |
| // 場合の受け皿。発火条件は次の3点が全て揃ったティック: | |
| // (1) 意図のセットから REPLY_FALLBACK_WAIT_MS 以上が経っている | |
| // (2) 直前まで相手が静か(SILENT_LISTEN が REPLY_FALLBACK_SILENCE_TICKS 連続) | |
| // (3) 現在のティックの argmax も SILENT_LISTEN(床が開いている) | |
| // そのティックで意図を直接配送する。相手が言い終わって間が空いた静けさ自体が | |
| // 「どうぞ」の合図であり、相槌の気まぐれを待つ必要はない、という設計変更。 | |
| // 発話ブロック中(now < busyUntil)はバークと同じくゲートを通さない。 | |
| if (name === 'SILENT_LISTEN' && this.intents.intent && this.intents.intent.kind === 'reply' && now >= this.busyUntil) { | |
| const waitedMs = now - (this.intents.intent.setAt ?? now); | |
| if (waitedMs >= REPLY_FALLBACK_WAIT_MS && silenceStreakBefore >= REPLY_FALLBACK_SILENCE_TICKS) { | |
| const intent = this.intents.takeForTurn(now); | |
| if (intent) { | |
| const morae = this.splitMora(intent.text); | |
| if (morae) { | |
| this.log(`意図: [${intent.tag}] を保険(床開き)で発話(${(waitedMs / 1000).toFixed(1)}秒待機・直前は静寂${silenceStreakBefore}ティック)`); | |
| await this.speakMorae(morae, intent.rateMul, intent.pitchOffsetHz, intent.show || intent.text); | |
| return { action: 'SILENT_LISTEN(fallback)', said: intent.text, via: 'intent', route: 'fallback' }; | |
| } | |
| this.log(`意図: [${intent.tag}] のモーラ分割に失敗したため破棄`); | |
| } | |
| } | |
| } | |
| if (name === 'SILENT_LISTEN') return { action: name }; | |
| if (name === 'BACKCHANNEL' && now - this.lastBcAt < BC_GUARD_MS) { | |
| this.stats.bcSuppressed++; | |
| return { action: name, held: 'bc-guard' }; | |
| } | |
| // turnHasSpoken(ベンチ層 (3)):発話後、SILENCE 10 連続でフラグが落ちるまで CONTINUE の発話実行を抑止 | |
| if (name === 'CONTINUE' && this.turnHasSpoken) { | |
| this.stats.contSuppressed++; | |
| return { action: name, held: 'turn-has-spoken' }; | |
| } | |
| // 発話経路:TAKE_TURN では意図を優先し、無ければ語彙バンクから選ぶ。 | |
| // ただしここで消費してよいのは返事意図のみ。状況意図の配送は上のバーク経路の | |
| // 専管で、特に quietOnly の状況意図はバーク側で「静かなティックまで保持」と | |
| // 判断されたものがここに吸い込まれると、誰かが喋っている最中に踏んでしまう | |
| // (被り修復の契約違反)。種別を見てから取る。 | |
| if (name === 'TAKE_TURN' && this.intents.intent && this.intents.intent.kind === 'reply') { | |
| const intent = this.intents.takeForTurn(now); | |
| if (intent) { | |
| const morae = this.splitMora(intent.text); | |
| if (morae) { | |
| this.log(`意図: [${intent.tag}] をターン経路で発話`); | |
| await this.speakMorae(morae, intent.rateMul, intent.pitchOffsetHz, intent.show || intent.text); | |
| return { action: name, said: intent.text, via: 'intent', route: 'turn' }; | |
| } | |
| } | |
| } | |
| const entry = name === 'BACKCHANNEL' | |
| ? this.selectBcEntry(queryVec, now) | |
| : selectEntry(this.bank, name, queryVec); | |
| if (!entry) return { action: name }; | |
| const morae = this.splitMora(entry.kana); | |
| if (!morae) { this.log(`配線: モーラ分割に失敗 ${entry.id} ${entry.kana}`); return { action: name }; } | |
| if (name === 'BACKCHANNEL') { this.lastBcAt = now; this.noteBcUsed(entry.id, now); } | |
| // 自声区間の種類:相槌だけ 'bc'、語彙経路のそれ以外(TAKE_TURN/CONTINUE/ | |
| // NONVERBAL 等)は 'main'。意図配送側の発話は全て 'main'(既定値)。 | |
| await this.speakMorae(morae, entry.rateMul, entry.pitchOffsetHz, entry.display, name === 'BACKCHANNEL' ? 'bc' : 'main'); | |
| return { action: name, said: entry.display, via: 'lexicon', id: entry.id }; | |
| } | |
| } | |