somora 2026.930.1
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/LICENSE +21 -0
- package/README.md +364 -0
- package/bin/node-version.d.mts +3 -0
- package/bin/node-version.mjs +45 -0
- package/bin/somora.mjs +77 -0
- package/config.example.yaml +896 -0
- package/docs/agents.md +677 -0
- package/docs/api.md +3194 -0
- package/docs/browser.md +317 -0
- package/docs/builder.md +331 -0
- package/docs/cache-strategy.md +373 -0
- package/docs/compaction.md +253 -0
- package/docs/display.md +154 -0
- package/docs/dream-phases.md +891 -0
- package/docs/files.md +387 -0
- package/docs/imagegen.md +366 -0
- package/docs/images/somora-hero.png +0 -0
- package/docs/images/somora-mobile-2026-05-23.png +0 -0
- package/docs/images/somora-tui-2026-05-23.png +0 -0
- package/docs/images/somora-web-2026-05-23.png +0 -0
- package/docs/index.md +178 -0
- package/docs/lsp.md +93 -0
- package/docs/mcp.md +332 -0
- package/docs/memory.md +407 -0
- package/docs/mobile.md +310 -0
- package/docs/models.md +379 -0
- package/docs/projects.md +425 -0
- package/docs/realtime-voice.md +293 -0
- package/docs/resources.md +230 -0
- package/docs/sampling.md +128 -0
- package/docs/security.md +189 -0
- package/docs/sentinel.md +295 -0
- package/docs/setup.md +1217 -0
- package/docs/skills.md +501 -0
- package/docs/team.md +189 -0
- package/docs/thinking.md +463 -0
- package/docs/tmux.md +399 -0
- package/docs/tools.md +117 -0
- package/docs/videogen.md +191 -0
- package/docs/voice.md +288 -0
- package/docs/web.md +893 -0
- package/docs/wiki.md +583 -0
- package/npm-shrinkwrap.json +5670 -0
- package/package.json +116 -0
- package/src/attachments/store.ts +196 -0
- package/src/browser/change-stream.ts +31 -0
- package/src/browser/display.ts +108 -0
- package/src/browser/policy.ts +121 -0
- package/src/browser/screencast.ts +374 -0
- package/src/browser/service.ts +1337 -0
- package/src/browser/session.ts +15 -0
- package/src/browser/snapshot.ts +40 -0
- package/src/cli/auth.ts +117 -0
- package/src/cli/codex.ts +41 -0
- package/src/cli/lsp.ts +71 -0
- package/src/cli/resolvers/clawhub.ts +400 -0
- package/src/cli/setup.ts +835 -0
- package/src/cli/skill.ts +619 -0
- package/src/cli/somora.ts +548 -0
- package/src/cli/systemd-unit.ts +72 -0
- package/src/cli/team.ts +148 -0
- package/src/cli/tui/activity-stream.ts +121 -0
- package/src/cli/tui/api.ts +479 -0
- package/src/cli/tui/app.tsx +1169 -0
- package/src/cli/tui/autocomplete.tsx +55 -0
- package/src/cli/tui/commands.ts +913 -0
- package/src/cli/tui/dream-glyphs.ts +22 -0
- package/src/cli/tui/footer.tsx +15 -0
- package/src/cli/tui/format.ts +28 -0
- package/src/cli/tui/header.tsx +279 -0
- package/src/cli/tui/index.tsx +120 -0
- package/src/cli/tui/markdown.tsx +63 -0
- package/src/cli/tui/sampling.ts +162 -0
- package/src/cli/tui/separator.tsx +13 -0
- package/src/cli/tui/state.ts +42 -0
- package/src/cli/tui/stream.ts +330 -0
- package/src/cli/tui/thinking-text.ts +54 -0
- package/src/cli/tui/turn-views.tsx +499 -0
- package/src/cli/tui/types.ts +410 -0
- package/src/cli/tui/work-queue.ts +161 -0
- package/src/cli/update-args.ts +55 -0
- package/src/cli/wiki.ts +406 -0
- package/src/compaction/index.ts +28 -0
- package/src/compaction/midturn.ts +210 -0
- package/src/compaction/policy.ts +154 -0
- package/src/compaction/summarize.ts +691 -0
- package/src/compaction/template.ts +90 -0
- package/src/compaction/types.ts +148 -0
- package/src/config/loader.ts +276 -0
- package/src/config/reload.ts +43 -0
- package/src/config/types.ts +2292 -0
- package/src/dream/deep-actions.ts +324 -0
- package/src/dream/deep-dispatcher.ts +237 -0
- package/src/dream/deep-llm.ts +388 -0
- package/src/dream/deep-prompts.ts +106 -0
- package/src/dream/deep-runner.ts +757 -0
- package/src/dream/deep-skip-cache.ts +199 -0
- package/src/dream/deep-worker.ts +229 -0
- package/src/dream/json-salvage.ts +34 -0
- package/src/dream/judge.ts +188 -0
- package/src/dream/loop-state.ts +286 -0
- package/src/dream/lucid-actions.ts +303 -0
- package/src/dream/lucid-batches.ts +94 -0
- package/src/dream/lucid-prompt.ts +82 -0
- package/src/dream/lucid-runner.ts +744 -0
- package/src/dream/lucid-storage.ts +277 -0
- package/src/dream/lucid-structure.ts +102 -0
- package/src/dream/lucid-types.ts +137 -0
- package/src/dream/lucid-worker.ts +224 -0
- package/src/dream/rem-dedup.ts +502 -0
- package/src/dream/rem-extract.ts +782 -0
- package/src/dream/rem-reset-run.ts +67 -0
- package/src/dream/rem-runner.ts +696 -0
- package/src/dream/rem-worker.ts +527 -0
- package/src/dream/review-window.ts +71 -0
- package/src/dream/scheduler-state.ts +129 -0
- package/src/dream/storage.ts +497 -0
- package/src/dream/types.ts +133 -0
- package/src/dream/wiki-context.ts +133 -0
- package/src/engine/a2a.ts +33 -0
- package/src/engine/availability.ts +63 -0
- package/src/engine/claude-cli.ts +969 -0
- package/src/engine/codex-app-server-client.ts +294 -0
- package/src/engine/codex-bin.ts +49 -0
- package/src/engine/codex-cli.ts +1014 -0
- package/src/engine/codex-dynamic-tools.ts +239 -0
- package/src/engine/codex-home.ts +63 -0
- package/src/engine/codex-thread-config.ts +74 -0
- package/src/engine/context-budget.ts +257 -0
- package/src/engine/engine-meta-labels.ts +211 -0
- package/src/engine/grok-cli.ts +941 -0
- package/src/engine/inline-think.ts +59 -0
- package/src/engine/model-availability.ts +105 -0
- package/src/engine/openai-compatible.ts +2464 -0
- package/src/engine/reasoning-retry.ts +83 -0
- package/src/engine/registry.ts +13 -0
- package/src/engine/replay.ts +195 -0
- package/src/engine/sampling.ts +90 -0
- package/src/engine/thinking-params.ts +264 -0
- package/src/engine/types.ts +269 -0
- package/src/engine/user-tag.ts +24 -0
- package/src/imagegen/aspect.ts +128 -0
- package/src/imagegen/generate.ts +642 -0
- package/src/imagegen/references.ts +75 -0
- package/src/imagegen/types.ts +154 -0
- package/src/lsp/client.ts +183 -0
- package/src/lsp/fake-server.helper.mjs +42 -0
- package/src/lsp/format.ts +29 -0
- package/src/lsp/index.ts +21 -0
- package/src/lsp/manager.ts +238 -0
- package/src/lsp/registry.ts +151 -0
- package/src/mcp/config.ts +117 -0
- package/src/mcp/hub/audit.ts +55 -0
- package/src/mcp/hub/bridge.ts +115 -0
- package/src/mcp/hub/catalog.ts +69 -0
- package/src/mcp/hub/credentials.ts +406 -0
- package/src/mcp/hub/env-expand.ts +14 -0
- package/src/mcp/hub/manager.ts +770 -0
- package/src/mcp/hub/normalize.ts +213 -0
- package/src/mcp/server.ts +368 -0
- package/src/mcp/tool-schema.ts +20 -0
- package/src/media/capabilities.ts +392 -0
- package/src/media/records.ts +175 -0
- package/src/media/store.ts +217 -0
- package/src/media/types.ts +69 -0
- package/src/memory/chunking.ts +168 -0
- package/src/memory/embeddings.ts +262 -0
- package/src/memory/index.ts +15 -0
- package/src/memory/inject.ts +197 -0
- package/src/memory/manager.ts +996 -0
- package/src/memory/registry.ts +176 -0
- package/src/memory/rescan.ts +101 -0
- package/src/memory/retrieval.ts +586 -0
- package/src/memory/shared-index.ts +372 -0
- package/src/memory/slug.ts +39 -0
- package/src/memory/storage.ts +385 -0
- package/src/memory/watcher.ts +134 -0
- package/src/multimodal/blocks.ts +101 -0
- package/src/multimodal/dimensions.ts +214 -0
- package/src/multimodal/load.ts +86 -0
- package/src/multimodal/mime.ts +135 -0
- package/src/multimodal/pdf-render.ts +80 -0
- package/src/multimodal/user-content.ts +266 -0
- package/src/persona/files.ts +144 -0
- package/src/persona/loader.ts +598 -0
- package/src/persona/skill-gating-store.ts +59 -0
- package/src/persona/tool-gating-store.ts +113 -0
- package/src/projects/focus.ts +186 -0
- package/src/projects/prompt-block.ts +106 -0
- package/src/projects/scheme.ts +107 -0
- package/src/projects/store.ts +144 -0
- package/src/projects/types.ts +73 -0
- package/src/sentinel/dispatcher.ts +97 -0
- package/src/sentinel/schedule.ts +271 -0
- package/src/sentinel/scheduler.ts +840 -0
- package/src/sentinel/store.ts +259 -0
- package/src/sentinel/types.ts +221 -0
- package/src/server/activity-stream.ts +160 -0
- package/src/server/ask-calls.ts +137 -0
- package/src/server/ask-wait-graph.ts +171 -0
- package/src/server/async-tasks.ts +199 -0
- package/src/server/builder-busy.ts +86 -0
- package/src/server/builder-prompt.ts +204 -0
- package/src/server/builder-questions.ts +117 -0
- package/src/server/builder-session.ts +249 -0
- package/src/server/chat-aborts.ts +83 -0
- package/src/server/claude-config-dir.ts +71 -0
- package/src/server/claude-credential-sync.ts +454 -0
- package/src/server/env-file.ts +100 -0
- package/src/server/env.ts +115 -0
- package/src/server/heal-session.ts +151 -0
- package/src/server/history-page.ts +46 -0
- package/src/server/index.ts +7244 -0
- package/src/server/lockfile.ts +89 -0
- package/src/server/logger.ts +67 -0
- package/src/server/logs.ts +187 -0
- package/src/server/loopback-fetch.ts +130 -0
- package/src/server/openai-client.ts +89 -0
- package/src/server/prompt-assembly.ts +334 -0
- package/src/server/restart-reconcile.ts +139 -0
- package/src/server/run-turn-fallback.ts +275 -0
- package/src/server/run-turn-types.ts +91 -0
- package/src/server/run-turn.ts +1474 -0
- package/src/server/sanitize-assistant-text.ts +112 -0
- package/src/server/session-export.ts +220 -0
- package/src/server/session-queue.ts +376 -0
- package/src/server/session-workdir.ts +49 -0
- package/src/server/sse-h2-safe.ts +61 -0
- package/src/server/sse-liveness.ts +162 -0
- package/src/server/sse-serializer.ts +161 -0
- package/src/server/start-turn.ts +249 -0
- package/src/server/steer-inbox.ts +107 -0
- package/src/server/tls-keeper.ts +153 -0
- package/src/server/tool-format.ts +167 -0
- package/src/server/turn-framing.ts +52 -0
- package/src/server/turn-origin-kind.ts +74 -0
- package/src/server/turn-origin.ts +40 -0
- package/src/server/work-ledger.ts +975 -0
- package/src/server/workspace.ts +114 -0
- package/src/setup/config-edit.ts +201 -0
- package/src/setup/presets.ts +71 -0
- package/src/setup/prompt.ts +163 -0
- package/src/setup/tailscale.ts +44 -0
- package/src/skills/bin-checks.ts +227 -0
- package/src/skills/bootstrap.ts +347 -0
- package/src/skills/env-scope.ts +175 -0
- package/src/skills/gating.ts +71 -0
- package/src/skills/lint.ts +202 -0
- package/src/skills/load.ts +368 -0
- package/src/skills/path-helpers.ts +102 -0
- package/src/skills/registry.ts +178 -0
- package/src/ssh/exec.ts +142 -0
- package/src/ssh/index.ts +12 -0
- package/src/ssh/known-hosts.ts +109 -0
- package/src/ssh/pool.ts +307 -0
- package/src/storage/sessions.ts +602 -0
- package/src/team/render.ts +149 -0
- package/src/team/resolve.ts +122 -0
- package/src/team/store.ts +124 -0
- package/src/team/types.ts +111 -0
- package/src/team/write.ts +95 -0
- package/src/testing/isolated-home.mts +46 -0
- package/src/tmux/attention-watcher.ts +272 -0
- package/src/tmux/attention.ts +336 -0
- package/src/tmux/list.ts +91 -0
- package/src/tmux/origin-store.ts +102 -0
- package/src/tmux/tui-markers.ts +267 -0
- package/src/tools/agents/ask-cancel.ts +94 -0
- package/src/tools/agents/ask-result.ts +235 -0
- package/src/tools/agents/ask.ts +704 -0
- package/src/tools/agents/builder-dispatch.ts +217 -0
- package/src/tools/agents/images.ts +104 -0
- package/src/tools/agents/index.ts +42 -0
- package/src/tools/agents/long-task-timeouts.ts +39 -0
- package/src/tools/agents/session-list.ts +136 -0
- package/src/tools/agents/session-model.ts +106 -0
- package/src/tools/agents/spawn.ts +845 -0
- package/src/tools/agents/status.ts +589 -0
- package/src/tools/browser/index.ts +6 -0
- package/src/tools/browser/ops.ts +145 -0
- package/src/tools/browser/tools.ts +184 -0
- package/src/tools/builder/short-descriptions.ts +80 -0
- package/src/tools/builder/tools.ts +222 -0
- package/src/tools/docs/index.ts +1 -0
- package/src/tools/docs/tools.ts +228 -0
- package/src/tools/dream/index.ts +11 -0
- package/src/tools/dream/tools.ts +1002 -0
- package/src/tools/exec/allowlist.ts +233 -0
- package/src/tools/exec/background-detach.helper.mts +27 -0
- package/src/tools/exec/blacklist.ts +336 -0
- package/src/tools/exec/concurrency.ts +150 -0
- package/src/tools/exec/fit-output.ts +82 -0
- package/src/tools/exec/index.ts +7 -0
- package/src/tools/exec/internal-env.ts +89 -0
- package/src/tools/exec/job-store.ts +403 -0
- package/src/tools/exec/local.ts +649 -0
- package/src/tools/exec/remote.ts +399 -0
- package/src/tools/exec/tools.ts +934 -0
- package/src/tools/file/analyze.ts +378 -0
- package/src/tools/file/index.ts +2 -0
- package/src/tools/file/local.ts +707 -0
- package/src/tools/file/lsp-hook.ts +72 -0
- package/src/tools/file/persona-guard.ts +61 -0
- package/src/tools/file/policy.ts +292 -0
- package/src/tools/file/read-format.ts +129 -0
- package/src/tools/file/remote.ts +680 -0
- package/src/tools/file/replace.ts +507 -0
- package/src/tools/file/search-window.ts +224 -0
- package/src/tools/file/tools.ts +658 -0
- package/src/tools/file/write-scope.ts +182 -0
- package/src/tools/gating.ts +106 -0
- package/src/tools/image/budget.ts +82 -0
- package/src/tools/image/index.ts +7 -0
- package/src/tools/image/tools.ts +601 -0
- package/src/tools/index.ts +99 -0
- package/src/tools/memory/index.ts +12 -0
- package/src/tools/memory/tools.ts +399 -0
- package/src/tools/projects/index.ts +1 -0
- package/src/tools/projects/tools.ts +643 -0
- package/src/tools/registry.ts +427 -0
- package/src/tools/resources/index.ts +8 -0
- package/src/tools/resources/tools.ts +176 -0
- package/src/tools/resources/visibility.ts +60 -0
- package/src/tools/sentinel/index.ts +1 -0
- package/src/tools/sentinel/tools.ts +592 -0
- package/src/tools/skill/index.ts +4 -0
- package/src/tools/skill/tools.ts +285 -0
- package/src/tools/time/index.ts +5 -0
- package/src/tools/time/tools.ts +123 -0
- package/src/tools/tmux/index.ts +1 -0
- package/src/tools/tmux/local.ts +277 -0
- package/src/tools/tmux/remote.ts +168 -0
- package/src/tools/tmux/tools.ts +1064 -0
- package/src/tools/tool-output.ts +97 -0
- package/src/tools/types.ts +227 -0
- package/src/tools/video/index.ts +1 -0
- package/src/tools/video/tools.ts +425 -0
- package/src/tools/web/fetch.ts +337 -0
- package/src/tools/web/index.ts +4 -0
- package/src/tools/web/tools.ts +186 -0
- package/src/tools/wiki/index.ts +1 -0
- package/src/tools/wiki/tools.ts +445 -0
- package/src/tts/cache-gc.ts +128 -0
- package/src/tts/prepare-for-tts.ts +114 -0
- package/src/tts/service.ts +332 -0
- package/src/types/events.ts +695 -0
- package/src/types/turn-origin.ts +53 -0
- package/src/version.ts +21 -0
- package/src/videogen/dialects.ts +222 -0
- package/src/videogen/generate.ts +484 -0
- package/src/videogen/jobs.ts +178 -0
- package/src/videogen/runner.ts +125 -0
- package/src/videogen/wake.ts +119 -0
- package/src/voice/realtime/call.ts +948 -0
- package/src/voice/realtime/consult.ts +293 -0
- package/src/voice/realtime/fake-provider.ts +134 -0
- package/src/voice/realtime/manager.ts +384 -0
- package/src/voice/realtime/openai-provider.ts +471 -0
- package/src/voice/realtime/persona.ts +227 -0
- package/src/voice/realtime/session-match.ts +116 -0
- package/src/voice/realtime/types.ts +182 -0
- package/src/wiki/conflict.ts +113 -0
- package/src/wiki/explorer.ts +578 -0
- package/src/wiki/index-builder.ts +172 -0
- package/src/wiki/language.ts +134 -0
- package/src/wiki/log-builder.ts +150 -0
- package/src/wiki/map.ts +258 -0
- package/src/wiki/migration/analyze.ts +304 -0
- package/src/wiki/migration/execute.ts +689 -0
- package/src/wiki/migration/refine.ts +402 -0
- package/src/wiki/migration/store.ts +100 -0
- package/src/wiki/move-page.ts +57 -0
- package/src/wiki/structure-file.ts +192 -0
- package/src/wiki/taxonomy.ts +140 -0
- package/src/wiki/templates.ts +163 -0
- package/src/wiki/types.ts +133 -0
- package/templates/skills/README.md +24 -0
- package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
- package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
- package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
- package/templates/skills/_templates/default/SKILL.md +25 -0
- package/templates/skills/builder-handover/SKILL.md +96 -0
- package/templates/skills/builder-handover/assets/ORDER.md +12 -0
- package/templates/skills/skill-author/SKILL.md +110 -0
- package/tsconfig.json +22 -0
- package/web/dist/assets/index-BaVv6pB2.js +631 -0
- package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
- package/web/dist/assets/index-V3FV3Z25.css +32 -0
- package/web/dist/favicon.svg +8 -0
- package/web/dist/index.html +20 -0
- package/web/package.json +36 -0
- package/web/tsconfig.json +25 -0
- package/web-mobile/dist/apple-touch-icon.png +0 -0
- package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
- package/web-mobile/dist/favicon.svg +8 -0
- package/web-mobile/dist/icon-192.png +0 -0
- package/web-mobile/dist/icon-512.png +0 -0
- package/web-mobile/dist/index.html +27 -0
- package/web-mobile/dist/manifest.webmanifest +32 -0
- package/web-mobile/dist/service-worker.js +90 -0
- package/web-mobile/package.json +28 -0
- package/web-mobile/tsconfig.json +25 -0
|
@@ -0,0 +1,948 @@
|
|
|
1
|
+
// One voice call: a standing conversation bound to one agent and one
|
|
2
|
+
// session, in which a second model does the talking and the real agent
|
|
3
|
+
// does the knowing.
|
|
4
|
+
//
|
|
5
|
+
// The state machine lives here, deliberately free of any provider and
|
|
6
|
+
// of the HTTP server, so it can be driven by a fake provider in a test
|
|
7
|
+
// and by a real one in production without a second implementation.
|
|
8
|
+
//
|
|
9
|
+
// Design: private/realtime-voice-design.md
|
|
10
|
+
|
|
11
|
+
import { randomUUID } from 'node:crypto';
|
|
12
|
+
import type { Persona } from '../../persona/loader.ts';
|
|
13
|
+
import type { NormalizedEvent } from '../../types/events.ts';
|
|
14
|
+
import {
|
|
15
|
+
CONSULT_TOOL_NAME,
|
|
16
|
+
RESULT_TOOL_NAME,
|
|
17
|
+
parseResultArgs,
|
|
18
|
+
resultToolSpec,
|
|
19
|
+
STATUS_TOOL_NAME,
|
|
20
|
+
SWITCH_TOOL_NAME,
|
|
21
|
+
consultToolSpec,
|
|
22
|
+
parseConsultArgs,
|
|
23
|
+
parseSwitchArgs,
|
|
24
|
+
renderConsultTurn,
|
|
25
|
+
statusToolSpec,
|
|
26
|
+
switchToolSpec,
|
|
27
|
+
} from './consult.ts';
|
|
28
|
+
import { languageName, buildVoiceInstructions } from './persona.ts';
|
|
29
|
+
import { normalizeSpokenName } from './session-match.ts';
|
|
30
|
+
import type { RealtimeEvent, RealtimeProvider, RealtimeSession } from './types.ts';
|
|
31
|
+
|
|
32
|
+
/** How much of the conversation the call keeps in memory. */
|
|
33
|
+
/** An announcement waits for this much quiet from the caller … */
|
|
34
|
+
const ANNOUNCE_PAUSE_MS = 1_500;
|
|
35
|
+
/** … but not forever. */
|
|
36
|
+
const ANNOUNCE_MAX_WAIT_MS = 60_000;
|
|
37
|
+
const TRANSCRIPT_MEMORY = 24;
|
|
38
|
+
/** How much of it travels with a question to the agent. Six lines is
|
|
39
|
+
* about two exchanges: enough for "and how long does that take", short
|
|
40
|
+
* enough that it does not dominate the session it is written into. */
|
|
41
|
+
const CONSULT_TRANSCRIPT_LINES = 6;
|
|
42
|
+
|
|
43
|
+
export type VoiceCallState =
|
|
44
|
+
| 'connecting'
|
|
45
|
+
| 'listening'
|
|
46
|
+
| 'consulting'
|
|
47
|
+
| 'speaking'
|
|
48
|
+
| 'closed';
|
|
49
|
+
|
|
50
|
+
export interface VoiceCallTarget {
|
|
51
|
+
agent: string;
|
|
52
|
+
/** Resolved session id, never a slug — resolution happens before the
|
|
53
|
+
* call starts so a typo cannot become a new conversation. */
|
|
54
|
+
session: string;
|
|
55
|
+
/** For display and for the instructions. */
|
|
56
|
+
slug: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface ConsultResult {
|
|
60
|
+
text: string;
|
|
61
|
+
outcome?: string;
|
|
62
|
+
/** For correlating a spoken answer with the turn it came from. */
|
|
63
|
+
turnId?: string;
|
|
64
|
+
/**
|
|
65
|
+
* The turn did not finish inside the call's patience, or the session
|
|
66
|
+
* was busy with older work. The answer is a status, not a result —
|
|
67
|
+
* the work keeps running and lands in the session either way.
|
|
68
|
+
*/
|
|
69
|
+
pending?: boolean;
|
|
70
|
+
/** Phase 2 (2026-09-13): `answered` came back inside the patience;
|
|
71
|
+
* `handed_over` means the work goes on under `consultId` and the
|
|
72
|
+
* answer is delivered to the call when it lands. */
|
|
73
|
+
state?: 'answered' | 'handed_over';
|
|
74
|
+
consultId?: string;
|
|
75
|
+
/** Place in the session's queue at hand-over (0 = already running). */
|
|
76
|
+
position?: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** What a handed-over consult looks like when the voice asks for it. */
|
|
80
|
+
export interface ConsultLookup {
|
|
81
|
+
state: 'pending' | 'done' | 'failed';
|
|
82
|
+
text?: string;
|
|
83
|
+
error?: string;
|
|
84
|
+
position?: number;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** A finished consult, brought to the call by the work ledger. */
|
|
88
|
+
export interface ConsultDelivery {
|
|
89
|
+
consultId: string;
|
|
90
|
+
state: 'done' | 'failed';
|
|
91
|
+
text?: string;
|
|
92
|
+
error?: string;
|
|
93
|
+
/** Work the consult started finished after its answer (work-ledger
|
|
94
|
+
* maybeFollowUp): read out as a follow-up, even though the consult
|
|
95
|
+
* itself was already delivered. */
|
|
96
|
+
followUp?: boolean;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface SessionWorkStatus {
|
|
100
|
+
busy: boolean;
|
|
101
|
+
/** How long the current work has been running. */
|
|
102
|
+
sinceMs?: number;
|
|
103
|
+
/** Anything waiting behind it. */
|
|
104
|
+
queued?: number;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export interface VoiceCallDeps {
|
|
108
|
+
provider: RealtimeProvider;
|
|
109
|
+
/** Runs ONE turn in the bound session, as `from_system: 'voice'`.
|
|
110
|
+
* `prefix` is scaffolding the model sees and the record does not. */
|
|
111
|
+
runConsult(args: { agent: string; session: string; text: string; prefix?: string; callId?: string }): Promise<ConsultResult>;
|
|
112
|
+
/**
|
|
113
|
+
* Persists into the bound session's history AND puts it on the live
|
|
114
|
+
* stream.
|
|
115
|
+
*
|
|
116
|
+
* Both, or the chat window tells two different stories: during a call
|
|
117
|
+
* it showed only what the consult turn published, and a reload then
|
|
118
|
+
* added what had been on disk all along (Rene, 2026-09-12: "es war
|
|
119
|
+
* vorher anders gerendert … erst nach einem browser reload so").
|
|
120
|
+
* Whatever is written is published.
|
|
121
|
+
*
|
|
122
|
+
* Used for the handover note only. Everything the call says and hears
|
|
123
|
+
* stays in the call; what a session records is the question that
|
|
124
|
+
* reached the agent and the answer it gave.
|
|
125
|
+
*/
|
|
126
|
+
appendEvent(agent: string, session: string, ev: NormalizedEvent): Promise<void>;
|
|
127
|
+
/** Is the bound session busy, and for how long? Must not wait. */
|
|
128
|
+
sessionStatus?(agent: string, session: string): Promise<SessionWorkStatus>;
|
|
129
|
+
/** A handed-over consult by id — reading it counts as fetched. */
|
|
130
|
+
consultResult?(consultId: string): Promise<ConsultLookup | null>;
|
|
131
|
+
/** The call read (or announced) a consult; no second delivery. */
|
|
132
|
+
markConsultFetched?(consultId: string): Promise<void>;
|
|
133
|
+
/** Agents this call may be handed over to. Empty = switching off. */
|
|
134
|
+
callableAgents?: readonly string[];
|
|
135
|
+
/** Everything a call needs to continue as another agent. Rejects with
|
|
136
|
+
* a message the voice can say when the target does not exist. */
|
|
137
|
+
resolveTarget?(agent: string, sessionRef: string | undefined): Promise<{
|
|
138
|
+
persona: Persona;
|
|
139
|
+
target: VoiceCallTarget;
|
|
140
|
+
cfg: VoiceCallConfig;
|
|
141
|
+
}>;
|
|
142
|
+
/**
|
|
143
|
+
* Every provider event, as the call processes it.
|
|
144
|
+
*
|
|
145
|
+
* There is exactly ONE consumer of the provider's event stream — this
|
|
146
|
+
* class. An async generator hands each event to whoever asks first,
|
|
147
|
+
* so a second reader (the route forwarding frames to the browser)
|
|
148
|
+
* does not mirror the stream, it STEALS half of it. Measured through
|
|
149
|
+
* the deployed server on 2026-09-11: the call machine got the tool
|
|
150
|
+
* call and ran the turn while the browser saw neither transcript nor
|
|
151
|
+
* audio. Anything that needs to watch a call subscribes here.
|
|
152
|
+
*/
|
|
153
|
+
onEvent?(ev: RealtimeEvent, snapshot: VoiceCallSnapshot): void;
|
|
154
|
+
/**
|
|
155
|
+
* The call's own state, whenever it changes.
|
|
156
|
+
*
|
|
157
|
+
* Separate from `onEvent` because the interesting states are the ones
|
|
158
|
+
* NO provider event announces: "asking the agent" begins when somora
|
|
159
|
+
* decides to run a turn and ends when the turn returns. A watcher
|
|
160
|
+
* that only mirrors provider events sees connecting → listening →
|
|
161
|
+
* speaking and never learns why the pause in the middle happened
|
|
162
|
+
* (measured through the deployed server, 2026-09-11).
|
|
163
|
+
*/
|
|
164
|
+
onState?(snapshot: VoiceCallSnapshot): void;
|
|
165
|
+
log?(entry: Record<string, unknown>): void;
|
|
166
|
+
now?(): number;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export interface VoiceCallConfig {
|
|
170
|
+
model: string;
|
|
171
|
+
voice: string;
|
|
172
|
+
language: string;
|
|
173
|
+
consultPolicy: 'auto' | 'substantive' | 'always';
|
|
174
|
+
maxCallMinutes: number;
|
|
175
|
+
/** Interruption sensitivity, from config. */
|
|
176
|
+
turnDetection?: { threshold: number; prefixPaddingMs: number; silenceDurationMs: number };
|
|
177
|
+
/** Hand-written character from VOICE.md, when there is one. */
|
|
178
|
+
personaOverride?: string;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export interface VoiceCallSnapshot {
|
|
182
|
+
id: string;
|
|
183
|
+
target: VoiceCallTarget;
|
|
184
|
+
state: VoiceCallState;
|
|
185
|
+
startedAt: number;
|
|
186
|
+
/** Consults asked and answered — the number that says whether the
|
|
187
|
+
* voice self is actually delegating. */
|
|
188
|
+
consults: number;
|
|
189
|
+
/** Sentences the caller has said in this call. Counted, not kept:
|
|
190
|
+
* the session records the questions that reached the agent. */
|
|
191
|
+
spokenTurns: number;
|
|
192
|
+
/** Set while a handover is in flight: who the call is moving to.
|
|
193
|
+
* `target` still names the agent that is talking until the new one
|
|
194
|
+
* is actually on the line. */
|
|
195
|
+
handoverTo?: string;
|
|
196
|
+
lastError?: string;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export class VoiceCall {
|
|
200
|
+
readonly id = randomUUID();
|
|
201
|
+
private state: VoiceCallState = 'connecting';
|
|
202
|
+
private session: RealtimeSession | undefined;
|
|
203
|
+
/** Set by the switch tool; the run loop picks it up when the old
|
|
204
|
+
* provider session ends. */
|
|
205
|
+
private pendingSwitch: { agent: string; session?: string } | undefined;
|
|
206
|
+
/**
|
|
207
|
+
* The conversation itself — kept here and nowhere else.
|
|
208
|
+
*
|
|
209
|
+
* Spoken sentences used to be appended into the agent's session as
|
|
210
|
+
* user messages, and what the voice said back as a meta row. That
|
|
211
|
+
* made three different readers stumble: the CLI engines drop a user
|
|
212
|
+
* turn that never got an answer, REM and recall saw every question
|
|
213
|
+
* twice (once as said, once as asked), and a sentence written outside
|
|
214
|
+
* the session lock could land inside a running turn and break its
|
|
215
|
+
* pair. Rene, 2026-09-12: "es ist viel viel wartbarer code".
|
|
216
|
+
*
|
|
217
|
+
* What a session records now is exactly what A2A records: the
|
|
218
|
+
* question this call put to the agent, and the agent's answer. The
|
|
219
|
+
* talking around it lives for the length of the call, the way
|
|
220
|
+
* OpenClaw keeps it on its call object.
|
|
221
|
+
*/
|
|
222
|
+
private transcript: Array<{ role: 'caller' | 'voice'; text: string }> = [];
|
|
223
|
+
/** Consults that came back handed over: what was asked, when, and
|
|
224
|
+
* for whom — a result for a previous agent is not read out as this
|
|
225
|
+
* one's after a switch. */
|
|
226
|
+
private openConsults = new Map<string, { question: string; startedAt: number; agent: string; fetched: boolean }>();
|
|
227
|
+
/** A result that landed before the hand-over was recorded (the turn
|
|
228
|
+
* finished in the same tick the patience ran out). */
|
|
229
|
+
private earlyDeliveries = new Map<string, ConsultDelivery>();
|
|
230
|
+
/** When the caller last said something — an announcement waits for a
|
|
231
|
+
* pause. */
|
|
232
|
+
private lastHeardAt = 0;
|
|
233
|
+
/**
|
|
234
|
+
* Who the window is showing. Lags `target` across a handover.
|
|
235
|
+
*
|
|
236
|
+
* The old agent's last sentence is still in the browser's playback
|
|
237
|
+
* queue when the new provider session opens. Announcing the new name
|
|
238
|
+
* at that moment makes lisa finish her sentence under hans's name and
|
|
239
|
+
* colour (Rene, 2026-09-12: "es spricht aber noch Lisa"). The call
|
|
240
|
+
* says who is on the line only once that is true; the browser adds
|
|
241
|
+
* its own queue to the same question.
|
|
242
|
+
*/
|
|
243
|
+
private announced: VoiceCallTarget;
|
|
244
|
+
/**
|
|
245
|
+
* Targets that could not be reached, and what to say about them.
|
|
246
|
+
*
|
|
247
|
+
* Every switch attempt ends the provider session so the next voice can
|
|
248
|
+
* start, so a target that does not resolve costs a restart. Asking for
|
|
249
|
+
* the same impossible thing twice must not cost a second one — the
|
|
250
|
+
* answer is already known and goes straight back to the model.
|
|
251
|
+
*/
|
|
252
|
+
private unreachable = new Map<string, string>();
|
|
253
|
+
private consults = 0;
|
|
254
|
+
private spokenTurns = 0;
|
|
255
|
+
private lastError: string | undefined;
|
|
256
|
+
private readonly startedAt: number;
|
|
257
|
+
private deadlineTimer: NodeJS.Timeout | undefined;
|
|
258
|
+
|
|
259
|
+
constructor(
|
|
260
|
+
private target: VoiceCallTarget,
|
|
261
|
+
private persona: Persona,
|
|
262
|
+
private cfg: VoiceCallConfig,
|
|
263
|
+
private readonly deps: VoiceCallDeps,
|
|
264
|
+
) {
|
|
265
|
+
this.startedAt = this.now();
|
|
266
|
+
this.announced = { ...target };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
private now(): number {
|
|
270
|
+
return this.deps.now ? this.deps.now() : Date.now();
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
private setState(next: VoiceCallState): void {
|
|
274
|
+
if (this.state === next) return;
|
|
275
|
+
this.state = next;
|
|
276
|
+
this.deps.onState?.(this.snapshot());
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Where this call may be moved: any agent the operator allowed —
|
|
281
|
+
* INCLUDING the one already on the line.
|
|
282
|
+
*
|
|
283
|
+
* Filtering itself out made a whole dimension unreachable: an agent
|
|
284
|
+
* has many sessions, and "put me into your cerebrocraft session" was
|
|
285
|
+
* impossible while the tool only offered other agents (Rene,
|
|
286
|
+
* 2026-09-12). Same agent plus a different session is a move like any
|
|
287
|
+
* other; the voice stays the same, the conversation does not.
|
|
288
|
+
*/
|
|
289
|
+
private switchable(): string[] {
|
|
290
|
+
return [...(this.deps.callableAgents ?? [])];
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Is this name just the session the call is already in?
|
|
295
|
+
*
|
|
296
|
+
* The voice self knows which session it sits in, and on a handover it
|
|
297
|
+
* passes that name along unless something stops it — which is how
|
|
298
|
+
* asking for naxon landed in naxon's "cerebrocraft", because lisa had
|
|
299
|
+
* been in hers (Rene, 2026-09-12: "es muss nicht immer zwingend der
|
|
300
|
+
* fall sein das der andere agent überhaupt eine session hat die so
|
|
301
|
+
* benannt ist"). Nobody said that name, so it is not a wish.
|
|
302
|
+
*
|
|
303
|
+
* Anything ELSE the model passes did not come from itself, so it came
|
|
304
|
+
* from the caller and is taken at face value. An earlier version
|
|
305
|
+
* checked the name against the transcript instead and threw away a
|
|
306
|
+
* real wish: speech recognition wrote the session differently than the
|
|
307
|
+
* model did, and the two never matched.
|
|
308
|
+
*/
|
|
309
|
+
private isOwnSessionName(name: string): boolean {
|
|
310
|
+
return normalizeSpokenName(name) === normalizeSpokenName(this.target.slug);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
private log(entry: Record<string, unknown>): void {
|
|
314
|
+
this.deps.log?.({ call: this.id, agent: this.target.agent, session: this.target.session, ...entry });
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
snapshot(): VoiceCallSnapshot {
|
|
318
|
+
const moving = this.announced.agent !== this.target.agent || this.announced.slug !== this.target.slug;
|
|
319
|
+
return {
|
|
320
|
+
id: this.id,
|
|
321
|
+
target: this.announced,
|
|
322
|
+
...(moving ? { handoverTo: this.target.agent } : {}),
|
|
323
|
+
state: this.state,
|
|
324
|
+
startedAt: this.startedAt,
|
|
325
|
+
consults: this.consults,
|
|
326
|
+
spokenTurns: this.spokenTurns,
|
|
327
|
+
...(this.lastError ? { lastError: this.lastError } : {}),
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Open the provider session. The audio itself flows browser ↔
|
|
332
|
+
* provider; what comes back here is the control channel. */
|
|
333
|
+
async start(): Promise<RealtimeSession> {
|
|
334
|
+
const instructions = buildVoiceInstructions({
|
|
335
|
+
persona: this.persona,
|
|
336
|
+
consultPolicy: this.cfg.consultPolicy,
|
|
337
|
+
language: this.cfg.language,
|
|
338
|
+
consultToolName: CONSULT_TOOL_NAME,
|
|
339
|
+
sessionSlug: this.target.slug,
|
|
340
|
+
...(this.cfg.personaOverride ? { override: this.cfg.personaOverride } : {}),
|
|
341
|
+
// The instruction names the OTHERS — "ask for someone else" reads
|
|
342
|
+
// oddly with your own name in the list. The tool spec carries the
|
|
343
|
+
// full list, own name included, because moving to another session
|
|
344
|
+
// of yourself goes through the same call.
|
|
345
|
+
...(this.switchable().filter((a) => a !== this.target.agent).length > 0
|
|
346
|
+
? { switchTo: this.switchable().filter((a) => a !== this.target.agent) }
|
|
347
|
+
: {}),
|
|
348
|
+
});
|
|
349
|
+
this.log({
|
|
350
|
+
msg: 'voice.call_start',
|
|
351
|
+
model: this.cfg.model,
|
|
352
|
+
voice: this.cfg.voice,
|
|
353
|
+
instructionChars: instructions.chars,
|
|
354
|
+
personaSource: this.cfg.personaOverride ? 'VOICE.md' : 'derived',
|
|
355
|
+
});
|
|
356
|
+
this.session = await this.deps.provider.open({
|
|
357
|
+
model: this.cfg.model,
|
|
358
|
+
voice: this.cfg.voice,
|
|
359
|
+
instructions: instructions.text,
|
|
360
|
+
language: this.cfg.language,
|
|
361
|
+
...(this.cfg.turnDetection ? { turnDetection: this.cfg.turnDetection } : {}),
|
|
362
|
+
tools: [
|
|
363
|
+
consultToolSpec(this.persona.name),
|
|
364
|
+
statusToolSpec(),
|
|
365
|
+
resultToolSpec(),
|
|
366
|
+
...(this.switchable().length > 0 ? [switchToolSpec(this.switchable(), this.target.agent)] : []),
|
|
367
|
+
],
|
|
368
|
+
});
|
|
369
|
+
// The meter runs while nobody speaks, so the cap is wall-clock and
|
|
370
|
+
// enforced here rather than left to whoever forgets the tab.
|
|
371
|
+
//
|
|
372
|
+
// Measured from the START of the call, not of this session: start()
|
|
373
|
+
// runs again on every move. Re-arming it with the full budget would
|
|
374
|
+
// make a handover a way to talk for as long as you like, and leaving
|
|
375
|
+
// the old timer in place left one ticking per move.
|
|
376
|
+
this.clearDeadline();
|
|
377
|
+
const budgetLeft = Math.max(0, this.cfg.maxCallMinutes * 60_000 - (this.now() - this.startedAt));
|
|
378
|
+
this.deadlineTimer = setTimeout(
|
|
379
|
+
() => void this.close('call time limit reached'),
|
|
380
|
+
budgetLeft,
|
|
381
|
+
);
|
|
382
|
+
this.deadlineTimer.unref?.();
|
|
383
|
+
return this.session;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** Drive the call. Ends when the provider session ends. */
|
|
387
|
+
async *run(): AsyncGenerator<VoiceCallSnapshot> {
|
|
388
|
+
// The loop outlives a single provider session: handing the call to
|
|
389
|
+
// another agent means a new voice, and a voice cannot be changed
|
|
390
|
+
// once a session has spoken (measured 2026-09-11). So the call
|
|
391
|
+
// stays, the session underneath is replaced.
|
|
392
|
+
while (true) {
|
|
393
|
+
const session = this.session ?? (await this.start());
|
|
394
|
+
const ended = yield* this.pump(session);
|
|
395
|
+
if (!this.pendingSwitch) {
|
|
396
|
+
if (ended) return;
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
const request = this.pendingSwitch;
|
|
400
|
+
this.pendingSwitch = undefined;
|
|
401
|
+
const ok = await this.performSwitch(request);
|
|
402
|
+
yield this.snapshot();
|
|
403
|
+
if (!ok) return;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** One provider session's worth of events. Returns true when the call
|
|
408
|
+
* is over, false when it ended to make room for a switch. */
|
|
409
|
+
private async *pump(session: RealtimeSession): AsyncGenerator<VoiceCallSnapshot, boolean> {
|
|
410
|
+
for await (const ev of session.events()) {
|
|
411
|
+
// Mirror first, act second: a watcher must see the event even if
|
|
412
|
+
// handling it throws.
|
|
413
|
+
this.deps.onEvent?.(ev, this.snapshot());
|
|
414
|
+
switch (ev.kind) {
|
|
415
|
+
case 'ready':
|
|
416
|
+
// The new session is live, so the new name is now the honest
|
|
417
|
+
// one. Announced here rather than when the switch was decided.
|
|
418
|
+
this.announced = { ...this.target };
|
|
419
|
+
this.setState('listening');
|
|
420
|
+
this.deps.onState?.(this.snapshot());
|
|
421
|
+
yield this.snapshot();
|
|
422
|
+
break;
|
|
423
|
+
case 'model_speech':
|
|
424
|
+
this.setState(ev.phase === 'start' ? 'speaking' : 'listening');
|
|
425
|
+
yield this.snapshot();
|
|
426
|
+
break;
|
|
427
|
+
case 'user_transcript':
|
|
428
|
+
this.lastHeardAt = this.now();
|
|
429
|
+
if (ev.final && ev.text.trim().length > 0) {
|
|
430
|
+
this.remember('caller', ev.text.trim());
|
|
431
|
+
yield this.snapshot();
|
|
432
|
+
}
|
|
433
|
+
break;
|
|
434
|
+
case 'model_transcript':
|
|
435
|
+
if (ev.final && ev.text.trim().length > 0) {
|
|
436
|
+
this.remember('voice', ev.text.trim());
|
|
437
|
+
}
|
|
438
|
+
break;
|
|
439
|
+
case 'tool_call':
|
|
440
|
+
// Not awaited: a consult can take the whole patience, and the
|
|
441
|
+
// call must keep hearing the caller, honouring barge-in and
|
|
442
|
+
// taking the next question meanwhile (birdseye L10). The
|
|
443
|
+
// handler answers the tool call when it is done.
|
|
444
|
+
void this.handleToolCall(session, ev.callId, ev.name, ev.args).catch((err) => {
|
|
445
|
+
this.log({ msg: 'voice.tool_failed', tool: ev.name, err: (err as Error).message });
|
|
446
|
+
});
|
|
447
|
+
yield this.snapshot();
|
|
448
|
+
break;
|
|
449
|
+
case 'interrupted':
|
|
450
|
+
this.setState('listening');
|
|
451
|
+
this.log({ msg: 'voice.interrupted' });
|
|
452
|
+
yield this.snapshot();
|
|
453
|
+
break;
|
|
454
|
+
case 'error':
|
|
455
|
+
this.lastError = ev.message;
|
|
456
|
+
this.log({ msg: 'voice.error', err: ev.message, fatal: ev.fatal });
|
|
457
|
+
yield this.snapshot();
|
|
458
|
+
if (ev.fatal) {
|
|
459
|
+
await this.close(`provider error: ${ev.message}`);
|
|
460
|
+
return true;
|
|
461
|
+
}
|
|
462
|
+
break;
|
|
463
|
+
case 'closed':
|
|
464
|
+
if (this.pendingSwitch) return false;
|
|
465
|
+
this.setState('closed');
|
|
466
|
+
this.clearDeadline();
|
|
467
|
+
this.log({ msg: 'voice.call_end', reason: ev.reason, consults: this.consults, spokenTurns: this.spokenTurns });
|
|
468
|
+
yield this.snapshot();
|
|
469
|
+
return true;
|
|
470
|
+
default:
|
|
471
|
+
break;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
if (this.pendingSwitch) return false;
|
|
475
|
+
this.setState('closed');
|
|
476
|
+
this.clearDeadline();
|
|
477
|
+
yield this.snapshot();
|
|
478
|
+
return true;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Continue the same call somewhere else: another agent, or another
|
|
483
|
+
* session of the agent already on the line.
|
|
484
|
+
*
|
|
485
|
+
* A failure here used to end the call. It must not: the caller asked
|
|
486
|
+
* for a session that may not exist, and being hung up on for a typo
|
|
487
|
+
* is the worst possible answer. The call comes back as the agent it
|
|
488
|
+
* was and says so.
|
|
489
|
+
*/
|
|
490
|
+
private async performSwitch(request: { agent: string; session?: string }): Promise<boolean> {
|
|
491
|
+
const from = { ...this.target };
|
|
492
|
+
const fromPersona = this.persona;
|
|
493
|
+
const fromCfg = this.cfg;
|
|
494
|
+
const wanted = request.session;
|
|
495
|
+
// Carried over rather than asked for: dropped, so the caller lands
|
|
496
|
+
// in the other agent's main session.
|
|
497
|
+
const inherited = wanted !== undefined && request.agent !== this.target.agent && this.isOwnSessionName(wanted);
|
|
498
|
+
const session = inherited ? undefined : wanted;
|
|
499
|
+
if (inherited) {
|
|
500
|
+
this.log({ msg: 'voice.switch_session_dropped', to: request.agent, session: wanted });
|
|
501
|
+
}
|
|
502
|
+
try {
|
|
503
|
+
const next = await this.deps.resolveTarget!(request.agent, session);
|
|
504
|
+
await this.session?.close('handed over').catch(() => {});
|
|
505
|
+
this.session = undefined;
|
|
506
|
+
this.target = next.target;
|
|
507
|
+
this.persona = next.persona;
|
|
508
|
+
this.cfg = next.cfg;
|
|
509
|
+
this.setState('connecting');
|
|
510
|
+
this.deps.onState?.(this.snapshot());
|
|
511
|
+
await this.start();
|
|
512
|
+
this.log({ msg: 'voice.switched', from: `${from.agent}/${from.slug}`, to: `${this.target.agent}/${this.target.slug}` });
|
|
513
|
+
const moved = from.agent !== this.target.agent;
|
|
514
|
+
// A line in both places, so reading either conversation later
|
|
515
|
+
// shows where it went and where it came from. Moving between two
|
|
516
|
+
// sessions of the SAME agent writes the same pair — the agent is
|
|
517
|
+
// one, the conversations are two.
|
|
518
|
+
await this.note(
|
|
519
|
+
from.agent,
|
|
520
|
+
from.session,
|
|
521
|
+
moved
|
|
522
|
+
? `[voice] handed this call over to ${this.target.agent} (session "${this.target.slug}")`
|
|
523
|
+
: `[voice] this call moved to the "${this.target.slug}" session`,
|
|
524
|
+
);
|
|
525
|
+
await this.note(
|
|
526
|
+
this.target.agent,
|
|
527
|
+
this.target.session,
|
|
528
|
+
moved
|
|
529
|
+
? `[voice] took this call over from ${from.agent} (session "${from.slug}")`
|
|
530
|
+
: `[voice] this call came over from the "${from.slug}" session`,
|
|
531
|
+
);
|
|
532
|
+
return true;
|
|
533
|
+
} catch (err) {
|
|
534
|
+
this.lastError = (err as Error).message;
|
|
535
|
+
this.unreachable.set(`${request.agent}/${request.session ?? 'main'}`, this.lastError);
|
|
536
|
+
this.log({ msg: 'voice.switch_failed', to: request.agent, session: request.session ?? 'main', err: this.lastError });
|
|
537
|
+
// Back to where we were. The old provider session is already
|
|
538
|
+
// closing (the switch tool ends it so the new voice can start),
|
|
539
|
+
// so this opens a fresh one for the same agent.
|
|
540
|
+
try {
|
|
541
|
+
this.target = from;
|
|
542
|
+
this.persona = fromPersona;
|
|
543
|
+
this.cfg = fromCfg;
|
|
544
|
+
this.announced = { ...from };
|
|
545
|
+
this.setState('connecting');
|
|
546
|
+
const recovered = await this.start();
|
|
547
|
+
// The reason is the useful part: "there is main and cerebrocraft"
|
|
548
|
+
// is what lets the caller pick, where "that did not work" makes
|
|
549
|
+
// them guess again.
|
|
550
|
+
void recovered
|
|
551
|
+
.speak?.(
|
|
552
|
+
'Say ONE short sentence, in the language of this conversation: the move did not work and they are ' +
|
|
553
|
+
`still with you. Put this into your own words, briefly: ${this.lastError ?? 'the target could not be reached'}`,
|
|
554
|
+
)
|
|
555
|
+
.catch(() => {});
|
|
556
|
+
this.log({ msg: 'voice.switch_recovered', agent: from.agent, session: from.slug });
|
|
557
|
+
return true;
|
|
558
|
+
} catch (recoveryErr) {
|
|
559
|
+
this.log({ msg: 'voice.switch_recovery_failed', err: (recoveryErr as Error).message });
|
|
560
|
+
this.setState('closed');
|
|
561
|
+
this.clearDeadline();
|
|
562
|
+
return false;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* Come back on the line as the agent we already are.
|
|
569
|
+
*
|
|
570
|
+
* The switch tool ends its own provider session so the next voice can
|
|
571
|
+
* start, so "nothing to move to" is not a no-op: there is no session
|
|
572
|
+
* left to talk through. This opens a fresh one for the same target and
|
|
573
|
+
* has the voice say that the caller is still here.
|
|
574
|
+
*/
|
|
575
|
+
private async stayPut(reason: string): Promise<boolean> {
|
|
576
|
+
this.log({ msg: 'voice.switch_stayed', agent: this.target.agent, session: this.target.slug, reason });
|
|
577
|
+
try {
|
|
578
|
+
this.announced = { ...this.target };
|
|
579
|
+
this.setState('connecting');
|
|
580
|
+
const recovered = await this.start();
|
|
581
|
+
void recovered
|
|
582
|
+
.speak?.(
|
|
583
|
+
'Say ONE short sentence that they are still with you and ask which session they meant. Keep it under ten words.',
|
|
584
|
+
)
|
|
585
|
+
.catch(() => {});
|
|
586
|
+
return true;
|
|
587
|
+
} catch (err) {
|
|
588
|
+
this.log({ msg: 'voice.stay_failed', err: (err as Error).message });
|
|
589
|
+
this.setState('closed');
|
|
590
|
+
this.clearDeadline();
|
|
591
|
+
return false;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Microphone audio for whatever session the call is on RIGHT NOW.
|
|
597
|
+
*
|
|
598
|
+
* After a handover the provider session is a different object. The
|
|
599
|
+
* route used to hold the one it was given at the start, so once the
|
|
600
|
+
* call continued as another agent the microphone was still feeding a
|
|
601
|
+
* closed session: the window switched to lisa, lisa heard nothing,
|
|
602
|
+
* and the call had to be restarted (Rene, 2026-09-12). Anything that
|
|
603
|
+
* talks to the provider goes through the call, never around it.
|
|
604
|
+
*/
|
|
605
|
+
async sendAudio(chunk: { base64: string; rateHz: number }): Promise<void> {
|
|
606
|
+
await this.session?.sendAudio?.(chunk);
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
async interrupt(): Promise<void> {
|
|
610
|
+
await this.session?.interrupt();
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/**
|
|
614
|
+
* An answer that came back inside the patience goes to the talking
|
|
615
|
+
* model as a tool result. Handed the raw text, the small local model
|
|
616
|
+
* treated "shortened for the ear" as "leave it out": asked for the
|
|
617
|
+
* team structure, hans answered with 1239 characters and the voice
|
|
618
|
+
* spoke 25 (Rene, 2026-09-13). The hand-over announcement always
|
|
619
|
+
* carried an instruction; the quick path now does too — English,
|
|
620
|
+
* naming the call's language and the persona's sentence budget, the
|
|
621
|
+
* wording still the model's.
|
|
622
|
+
*/
|
|
623
|
+
private frameAnswer(text: string): string {
|
|
624
|
+
const sentences = this.persona.voice?.maxSpokenSentences ?? 4;
|
|
625
|
+
return (
|
|
626
|
+
`The agent answered. Tell the user the substance of this answer in ${languageName(this.cfg.language)}, ` +
|
|
627
|
+
`in at most ${sentences} sentences: the names, facts and numbers in it, as the agent gave them, ` +
|
|
628
|
+
'without reading lists or paths aloud. Never replace it with saying that you have it, that it is ' +
|
|
629
|
+
'done, or that it is in the chat.\n' +
|
|
630
|
+
text
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
private async note(agent: string, session: string, text: string): Promise<void> {
|
|
635
|
+
await this.deps.appendEvent(agent, session, {
|
|
636
|
+
kind: 'engine_meta',
|
|
637
|
+
ts: this.now(),
|
|
638
|
+
engine: 'voice',
|
|
639
|
+
itemType: 'voice_handover',
|
|
640
|
+
payload: { text },
|
|
641
|
+
} as NormalizedEvent);
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
private async handleToolCall(session: RealtimeSession, callId: string, name: string, rawArgs: string): Promise<void> {
|
|
645
|
+
if (name === STATUS_TOOL_NAME) {
|
|
646
|
+
const status = (await this.deps.sessionStatus?.(this.target.agent, this.target.session)) ?? { busy: false };
|
|
647
|
+
const minutes = status.sinceMs ? Math.max(1, Math.round(status.sinceMs / 60_000)) : 0;
|
|
648
|
+
const own: string[] = [];
|
|
649
|
+
for (const [id, c] of this.openConsults) {
|
|
650
|
+
if (c.fetched) continue;
|
|
651
|
+
const look = await this.deps.consultResult?.(id).catch(() => null);
|
|
652
|
+
if (look?.state === 'done' || look?.state === 'failed') {
|
|
653
|
+
// Reading it here counts as fetched: it is answered on this line.
|
|
654
|
+
c.fetched = true;
|
|
655
|
+
own.push(`your request "${c.question.slice(0, 80)}" is finished — answer: ${look.state === 'done' ? (look.text ?? '') : `could not: ${look.error ?? 'unknown error'}`}`);
|
|
656
|
+
} else if (look) {
|
|
657
|
+
own.push(`your request "${c.question.slice(0, 80)}" is still ${look.position ? `waiting (position ${look.position})` : 'running'}`);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
const base = status.busy
|
|
661
|
+
? `still working on something you started ${minutes} minute(s) ago${status.queued ? `, ${status.queued} waiting behind it` : ''} — say so, and offer to look again in a moment`
|
|
662
|
+
: 'nothing running right now';
|
|
663
|
+
await session.sendToolResult(callId, own.length > 0 ? `${base}; ${own.join('; ')}` : base);
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
if (name === RESULT_TOOL_NAME) {
|
|
667
|
+
const parsed = parseResultArgs(rawArgs);
|
|
668
|
+
if (!parsed.ok) {
|
|
669
|
+
await session.sendToolResult(callId, parsed.error);
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
const open = this.openConsults.get(parsed.consultId);
|
|
673
|
+
const look = await this.deps.consultResult?.(parsed.consultId).catch(() => null);
|
|
674
|
+
if (!look) {
|
|
675
|
+
await session.sendToolResult(callId, 'nothing was handed over under that id — say so');
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
if (look.state === 'pending') {
|
|
679
|
+
await session.sendToolResult(callId, `still working on it${look.position ? ` (position ${look.position} in the queue)` : ''} — say so, do not invent an answer`);
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
if (open) open.fetched = true;
|
|
683
|
+
this.log({ msg: 'voice.consult_fetched', consultId: parsed.consultId, state: look.state });
|
|
684
|
+
await session.sendToolResult(
|
|
685
|
+
callId,
|
|
686
|
+
look.state === 'done'
|
|
687
|
+
? (look.text?.trim() ? this.frameAnswer(look.text.trim()) : 'no answer this time — say so, do not invent one')
|
|
688
|
+
: `the agent could not answer: ${look.error ?? 'unknown error'}`,
|
|
689
|
+
);
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
if (name === SWITCH_TOOL_NAME) {
|
|
693
|
+
const parsed = parseSwitchArgs(rawArgs);
|
|
694
|
+
if (!parsed.ok) {
|
|
695
|
+
await session.sendToolResult(callId, parsed.error);
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
const allowed = this.switchable();
|
|
699
|
+
if (!allowed.includes(parsed.args.agent)) {
|
|
700
|
+
await session.sendToolResult(
|
|
701
|
+
callId,
|
|
702
|
+
`${parsed.args.agent} cannot be reached by voice — say so. Available: ${allowed.join(', ') || 'nobody else'}`,
|
|
703
|
+
);
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
const request = parsed.args;
|
|
707
|
+
// Already tried and already impossible: answer from memory rather
|
|
708
|
+
// than tearing the line down again.
|
|
709
|
+
const known = this.unreachable.get(`${request.agent}/${request.session ?? 'main'}`);
|
|
710
|
+
if (known) {
|
|
711
|
+
await session.sendToolResult(callId, known);
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
// Asking to go where you already are is a model slip, not a wish.
|
|
715
|
+
// Caught here because it is the one case decidable on the spot,
|
|
716
|
+
// and tearing a session down for it would be an audible pause for
|
|
717
|
+
// nothing.
|
|
718
|
+
const staying =
|
|
719
|
+
request.agent === this.target.agent &&
|
|
720
|
+
(request.session === undefined
|
|
721
|
+
? this.target.slug === 'main'
|
|
722
|
+
: request.session === this.target.slug);
|
|
723
|
+
if (staying) {
|
|
724
|
+
await session.sendToolResult(
|
|
725
|
+
callId,
|
|
726
|
+
'that is the conversation you are already in — say so, and ask which session they mean',
|
|
727
|
+
);
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
// Answer BEFORE the session goes away: the tool result has to
|
|
731
|
+
// reach the model that asked, not its successor.
|
|
732
|
+
await session.sendToolResult(
|
|
733
|
+
callId,
|
|
734
|
+
request.agent === this.target.agent
|
|
735
|
+
? `moving you into the "${request.session ?? 'main'}" session now`
|
|
736
|
+
: `putting them through to ${request.agent} now`,
|
|
737
|
+
);
|
|
738
|
+
this.pendingSwitch = request;
|
|
739
|
+
this.log({ msg: 'voice.switch_requested', to: request.agent, session: request.session ?? 'main' });
|
|
740
|
+
// Give the sentence a moment to be spoken, then end this session;
|
|
741
|
+
// the run loop opens the next one.
|
|
742
|
+
setTimeout(() => void session.close('handing over').catch(() => {}), 2_500).unref?.();
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
if (name !== CONSULT_TOOL_NAME) {
|
|
746
|
+
// The voice self only ever gets the tools we hand it. Anything
|
|
747
|
+
// else is a provider or prompt bug, and answering it with an
|
|
748
|
+
// error keeps the conversation alive instead of wedging it.
|
|
749
|
+
this.log({ msg: 'voice.unknown_tool', tool: name });
|
|
750
|
+
await session.sendToolResult(callId, `unknown tool '${name}' — you only have ${CONSULT_TOOL_NAME}`);
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
const parsed = parseConsultArgs(rawArgs);
|
|
754
|
+
if (!parsed.ok) {
|
|
755
|
+
this.log({ msg: 'voice.consult_bad_args', err: parsed.error });
|
|
756
|
+
await session.sendToolResult(callId, parsed.error);
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
this.setState('consulting');
|
|
760
|
+
this.consults += 1;
|
|
761
|
+
const startedAt = this.now();
|
|
762
|
+
const turn = renderConsultTurn(parsed.args, 'the user', this.recentTranscript());
|
|
763
|
+
this.log({ msg: 'voice.consult_start', question: parsed.args.question.slice(0, 160) });
|
|
764
|
+
// Fill the silence from here rather than asking the model to
|
|
765
|
+
// announce its own lookup: told to do that, it announced and never
|
|
766
|
+
// called (both models, 2026-09-11).
|
|
767
|
+
void session
|
|
768
|
+
.speak?.('Say ONE short sentence that you are looking it up right now. Nothing else, no promises about what you will find.')
|
|
769
|
+
.catch(() => {});
|
|
770
|
+
try {
|
|
771
|
+
const result = await this.deps.runConsult({
|
|
772
|
+
agent: this.target.agent,
|
|
773
|
+
session: this.target.session,
|
|
774
|
+
text: turn.text,
|
|
775
|
+
prefix: turn.prefix,
|
|
776
|
+
callId: this.id,
|
|
777
|
+
});
|
|
778
|
+
if (result.state === 'handed_over' && result.consultId) {
|
|
779
|
+
const id = result.consultId;
|
|
780
|
+
this.openConsults.set(id, { question: parsed.args.question, startedAt, agent: this.target.agent, fetched: false });
|
|
781
|
+
this.log({ msg: 'voice.consult_handed_over', consultId: id, position: result.position ?? 0, ms: this.now() - startedAt });
|
|
782
|
+
if (this.state !== 'closed' && session === this.session) {
|
|
783
|
+
await session.sendToolResult(
|
|
784
|
+
callId,
|
|
785
|
+
`handed over (consult ${id}${result.position ? `, position ${result.position} in the queue` : ''}). ` +
|
|
786
|
+
'Tell the user you passed it on and keep talking. The answer is read out to them when it ' +
|
|
787
|
+
`arrives; if they ask whether it is done, ${RESULT_TOOL_NAME} fetches it.`,
|
|
788
|
+
);
|
|
789
|
+
}
|
|
790
|
+
const early = this.earlyDeliveries.get(id);
|
|
791
|
+
if (early) {
|
|
792
|
+
this.earlyDeliveries.delete(id);
|
|
793
|
+
void this.deliver(early);
|
|
794
|
+
}
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
const answer = result.text.trim();
|
|
798
|
+
this.log({
|
|
799
|
+
msg: 'voice.consult_done',
|
|
800
|
+
ms: this.now() - startedAt,
|
|
801
|
+
outcome: result.outcome ?? null,
|
|
802
|
+
pending: result.pending ?? false,
|
|
803
|
+
chars: answer.length,
|
|
804
|
+
});
|
|
805
|
+
// The session may be gone or replaced by the time a long answer
|
|
806
|
+
// lands: never write into a closed line or the successor's.
|
|
807
|
+
if (this.state === 'closed' || session !== this.session) {
|
|
808
|
+
this.log({ msg: 'voice.consult_answer_after_session', ms: this.now() - startedAt });
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
await session.sendToolResult(
|
|
812
|
+
callId,
|
|
813
|
+
answer.length > 0
|
|
814
|
+
? this.frameAnswer(answer)
|
|
815
|
+
: `no answer this time — say so, do not invent one`,
|
|
816
|
+
);
|
|
817
|
+
} catch (err) {
|
|
818
|
+
const message = (err as Error).message;
|
|
819
|
+
this.lastError = message;
|
|
820
|
+
this.log({ msg: 'voice.consult_failed', err: message });
|
|
821
|
+
// The failure is told to the voice self so it can say something
|
|
822
|
+
// true ("I could not reach him"), rather than being swallowed
|
|
823
|
+
// into a silence the user has to interpret.
|
|
824
|
+
await session.sendToolResult(callId, `asking ${this.persona.name} failed: ${message}`);
|
|
825
|
+
} finally {
|
|
826
|
+
this.setState('listening');
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* A handed-over consult finished. Read it out — once, on this line,
|
|
832
|
+
* for the agent that was asked, at a pause in the conversation.
|
|
833
|
+
* Anything else stays in the agent's chat where it landed.
|
|
834
|
+
*/
|
|
835
|
+
async deliver(res: ConsultDelivery): Promise<void> {
|
|
836
|
+
const open = this.openConsults.get(res.consultId);
|
|
837
|
+
if (res.followUp) {
|
|
838
|
+
if (!open) {
|
|
839
|
+
this.log({ msg: 'voice.consult_delivery_skipped', consultId: res.consultId, reason: 'follow-up for a consult this call does not know' });
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
if (this.state === 'closed' || !this.session) {
|
|
843
|
+
this.log({ msg: 'voice.consult_delivery_skipped', consultId: res.consultId, reason: 'call closed' });
|
|
844
|
+
return;
|
|
845
|
+
}
|
|
846
|
+
if (open.agent !== this.target.agent) {
|
|
847
|
+
this.log({ msg: 'voice.consult_delivery_skipped', consultId: res.consultId, reason: 'call moved to another agent' });
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
await this.announce(open.question, res);
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
853
|
+
if (!open) {
|
|
854
|
+
// Finished before the hand-over was recorded: keep it for a moment.
|
|
855
|
+
this.earlyDeliveries.set(res.consultId, res);
|
|
856
|
+
setTimeout(() => this.earlyDeliveries.delete(res.consultId), 30_000).unref?.();
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
if (open.fetched) return;
|
|
860
|
+
if (this.state === 'closed' || !this.session) {
|
|
861
|
+
this.log({ msg: 'voice.consult_delivery_skipped', consultId: res.consultId, reason: 'call closed' });
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
if (open.agent !== this.target.agent) {
|
|
865
|
+
this.log({ msg: 'voice.consult_delivery_skipped', consultId: res.consultId, reason: 'call moved to another agent' });
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
open.fetched = true;
|
|
869
|
+
await this.deps.markConsultFetched?.(res.consultId).catch(() => {});
|
|
870
|
+
await this.announce(open.question, res);
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
/** Wait for a pause (the model not speaking, the caller quiet for a
|
|
874
|
+
* moment), then have the model read the answer. Never a fixed
|
|
875
|
+
* sentence: the instruction is English, names the call's language,
|
|
876
|
+
* and the wording is the model's (Rene, 2026-09-13). */
|
|
877
|
+
private async announce(question: string, res: ConsultDelivery): Promise<void> {
|
|
878
|
+
const deadline = this.now() + ANNOUNCE_MAX_WAIT_MS;
|
|
879
|
+
while (this.now() < deadline) {
|
|
880
|
+
if (this.state === 'closed') return;
|
|
881
|
+
const quiet = this.state === 'listening' && this.now() - this.lastHeardAt >= ANNOUNCE_PAUSE_MS;
|
|
882
|
+
if (quiet) break;
|
|
883
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
884
|
+
}
|
|
885
|
+
if (this.state === 'closed' || !this.session) return;
|
|
886
|
+
const body = res.state === 'done'
|
|
887
|
+
? (res.text?.trim() || 'the agent had no answer')
|
|
888
|
+
: `the agent could not answer: ${res.error ?? 'unknown error'}`;
|
|
889
|
+
const instruction = res.followUp
|
|
890
|
+
? `The agent has a follow-up on the question the user asked earlier about "${question.slice(0, 120)}": ` +
|
|
891
|
+
'work it had started for that question has now finished. ' +
|
|
892
|
+
`Start by saying, in ${this.cfg.language}, that this is a follow-up to that earlier question, ` +
|
|
893
|
+
'then give it as it is. Do not add anything else.\n' +
|
|
894
|
+
body
|
|
895
|
+
: `Read the user the answer to the question they asked earlier about "${question.slice(0, 120)}". ` +
|
|
896
|
+
`Start by saying, in ${this.cfg.language}, that this is the answer to that earlier question, ` +
|
|
897
|
+
'then give the answer as it is. Do not add anything else.\n' +
|
|
898
|
+
body;
|
|
899
|
+
try {
|
|
900
|
+
// deliver: the model may be mid-sentence (its own "still working"
|
|
901
|
+
// after a status check); the announcement is kept for the pause
|
|
902
|
+
// instead of dropped like a filler (2026-09-13, hans counting to
|
|
903
|
+
// forty went silent while the log said announced).
|
|
904
|
+
await this.session.speak?.(instruction, { deliver: true });
|
|
905
|
+
this.log({ msg: 'voice.consult_announced', consultId: res.consultId, state: res.state, chars: body.length, ...(res.followUp ? { followUp: true } : {}) });
|
|
906
|
+
} catch (err) {
|
|
907
|
+
this.log({ msg: 'voice.consult_announce_failed', consultId: res.consultId, err: (err as Error).message });
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/**
|
|
912
|
+
* One line of the conversation, held for the length of the call.
|
|
913
|
+
*
|
|
914
|
+
* Nothing here reaches disk. Its one job is to give the agent the
|
|
915
|
+
* couple of sentences around a question: asked "what time is it", the
|
|
916
|
+
* agent otherwise has no idea what the caller was talking about.
|
|
917
|
+
* OpenClaw hands its consulting agent the last twelve lines for the
|
|
918
|
+
* same reason.
|
|
919
|
+
*/
|
|
920
|
+
private remember(role: 'caller' | 'voice', text: string): void {
|
|
921
|
+
if (role === 'caller') this.spokenTurns += 1;
|
|
922
|
+
this.transcript.push({ role, text });
|
|
923
|
+
if (this.transcript.length > TRANSCRIPT_MEMORY) {
|
|
924
|
+
this.transcript.splice(0, this.transcript.length - TRANSCRIPT_MEMORY);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/** The tail of the conversation that travels with a question. Short
|
|
929
|
+
* on purpose: it is written into the agent's session, so it is part
|
|
930
|
+
* of the record and part of every later context. */
|
|
931
|
+
private recentTranscript(): Array<{ role: 'caller' | 'voice'; text: string }> {
|
|
932
|
+
return this.transcript.slice(-CONSULT_TRANSCRIPT_LINES);
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
private clearDeadline(): void {
|
|
936
|
+
if (this.deadlineTimer) clearTimeout(this.deadlineTimer);
|
|
937
|
+
this.deadlineTimer = undefined;
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
async close(reason: string): Promise<void> {
|
|
941
|
+
this.clearDeadline();
|
|
942
|
+
if (this.state !== 'closed') {
|
|
943
|
+
this.state = 'closed';
|
|
944
|
+
await this.session?.close(reason).catch(() => {});
|
|
945
|
+
this.log({ msg: 'voice.call_closed', reason, consults: this.consults, spokenTurns: this.spokenTurns });
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
}
|