From 1bdbc61f973f26a984c8851876a5b0f78f5d3db0 Mon Sep 17 00:00:00 2001 From: zhangyuian Date: Thu, 26 Nov 2026 16:01:25 +0800 Subject: [PATCH 1/5] Connect the experiment assistant to LabscriptAI MCP --- .github/workflows/moss-web.yml | 2 +- MOSS-LAB.md | 8 +- internal/experiment/README.i18n.yaml | 4 +- internal/experiment/README.md | 2 + internal/experiment/README.zh.md | 2 + internal/experiment/labscriptai-tools.mjs | 160 +++++ internal/experiment/plugin-client.mjs | 139 +++- internal/experiment/robot-control-plugin.mjs | 50 +- internal/experiment/robot-tools.mjs | 31 +- internal/experiment/runtime-plugin.mjs | 5 +- .../tests/labscriptai-tools.test.mjs | 131 ++++ .../experiment/tests/robot-control.test.mjs | 20 +- internal/xiaozhi/README.i18n.yaml | 4 +- internal/xiaozhi/README.md | 2 +- internal/xiaozhi/README.zh.md | 2 +- moss-model.patch.yml | 20 +- moss-start.mjs | 2 +- .../user-approval/README.i18n.yaml | 4 +- packages/interaction/user-approval/README.md | 2 +- .../interaction/user-approval/README.zh.md | 2 +- .../interaction/user-approval/src/index.ts | 11 +- .../user-approval/tests/approval.spec.ts | 11 + scripts/check-labscriptai.mjs | 4 + .../labscriptai-fixture.mjs | 29 + .../runtime.cordis.yml | 11 + .../moss-labscriptai-status/session.v4.jsonl | 22 + .../moss-labscriptai-status/snapshot.yml | 8 + .../system-prompt.expected.md | 3 + .../tool-schemas.expected.json | 606 ++++++++++++++++++ 29 files changed, 1230 insertions(+), 67 deletions(-) create mode 100644 internal/experiment/labscriptai-tools.mjs create mode 100644 internal/experiment/tests/labscriptai-tools.test.mjs create mode 100644 snapshots/session/moss-labscriptai-status/labscriptai-fixture.mjs create mode 100644 snapshots/session/moss-labscriptai-status/runtime.cordis.yml create mode 100644 snapshots/session/moss-labscriptai-status/session.v4.jsonl create mode 100644 snapshots/session/moss-labscriptai-status/snapshot.yml create mode 100644 snapshots/session/moss-labscriptai-status/system-prompt.expected.md create mode 100644 snapshots/session/moss-labscriptai-status/tool-schemas.expected.json diff --git a/.github/workflows/moss-web.yml b/.github/workflows/moss-web.yml index 8d122b3df3e..bccc91b4558 100644 --- a/.github/workflows/moss-web.yml +++ b/.github/workflows/moss-web.yml @@ -70,7 +70,7 @@ jobs: - name: Test experiment storage and preview resources run: node --import tsx/esm --test internal/experiment/tests/workflow.test.mjs internal/experiment/tests/agent-tools.test.mjs internal/experiment/tests/preview-resources.test.mjs internal/experiment/tests/robot-status-plugin.test.mjs internal/experiment/tests/robot-control.test.mjs internal/xiaozhi/*.test.mjs - name: Test plugin lock, recovery and download resources - run: node --import tsx/esm --test internal/experiment/tests/plugin-runtime.test.mjs internal/experiment/tests/preview-recovery.test.mjs internal/experiment/tests/install-readiness.test.mjs + run: node --import tsx/esm --test internal/experiment/tests/plugin-runtime.test.mjs internal/experiment/tests/preview-recovery.test.mjs internal/experiment/tests/install-readiness.test.mjs internal/experiment/tests/labscriptai-tools.test.mjs - uses: astral-sh/setup-uv@v7 with: cache-dependency-glob: labscriptai-ot.lock.json diff --git a/MOSS-LAB.md b/MOSS-LAB.md index bc09edf5b80..10d03567e62 100644 --- a/MOSS-LAB.md +++ b/MOSS-LAB.md @@ -29,7 +29,9 @@ node moss-start.mjs `.dsh-local/` 保存网页会话、实验数据库、插件安装和产物。升级前停止旧服务并备份此目录与 `.env`;保留已有数据库,不要用空目录覆盖。旧 `labscriptai-ot/.venv` 不再使用,确认没有独立用途后可自行删除。模拟及动画不代表机器人就绪;状态查询不会执行机器人动作。 -要在真机运行,在 `.env` 中配置 `OPENTRONS_URL` 和 `MOSS_ALLOW_LIVE_ROBOT=1`。在「实验助手」中分析当前协议后,明确要求运行,再在网页核对设备、实验版本和实体台面并确认。暂停和继续需要网页确认。可以直接停止当前会话的运行。断线后先查询原运行状态,再决定是否继续。 +「实验助手」读取 LabscriptAI 发布的工具和实验指引。在网页打开小智当前的实验会话,即可继续同一个实验。说“看台面”可按需调用插件拍照和识别。若识别缺依赖,可用 `MOSS_VISION_PYTHON` 指向装有插件视觉依赖的 Python。照片通过工作台的通用图片附件显示,取决于当前模型是否支持图片输入。 + +要在真机运行,在 `.env` 中配置 `OPENTRONS_URL` 和 `MOSS_ALLOW_LIVE_ROBOT=1`。分析当前协议,明确要求运行,再在网页核对设备、实验版本和实体台面。一次确认覆盖本次运行及 LabscriptAI 支持的小故障自动恢复。暂停和继续需要网页确认。可以直接停止当前会话的运行。断线后先查询原运行状态,再决定是否继续。 网页 CI 使用 `MOSS web` 工作流检查构建、类型、实验存储与预览资源,以及网页客户端启动。该工作流不部署网站或操作真实机器人;Windows 安装任务使用受限模型凭据验证已安装程序与两机型本地仿真。 @@ -60,7 +62,9 @@ New tasks default to the experiment assistant, which is also available in the mo `.dsh-local/` stores web sessions, experiments, plugin installations, and artifacts. Stop the old service and back up this directory and `.env` before upgrading; preserve the existing database. The old `labscriptai-ot/.venv` is no longer used; remove it only after checking for independent uses. Simulation and animation do not establish robot readiness; status queries do not move the robot. -For physical operation, set `OPENTRONS_URL` and `MOSS_ALLOW_LIVE_ROBOT=1` in `.env`. Analyze the current protocol in the experiment assistant, explicitly request a live run, then confirm the device, revision, and physical deck in the workbench. Pause and resume require confirmation. Stop is available for a run owned by the current conversation. Read the original run status after a lost connection before sending further actions. +The experiment assistant discovers the tools and instructions published by LabscriptAI. Open the active Xiaozhi conversation in the workbench to continue its experiment by text. Ask to see the deck to invoke the plugin's camera and recognition on demand. If recognition dependencies are missing, set `MOSS_VISION_PYTHON` to a Python interpreter with the plugin's vision dependencies. The workbench uses its shared image attachment path when the selected model supports image input. + +For physical operation, set `OPENTRONS_URL` and `MOSS_ALLOW_LIVE_ROBOT=1` in `.env`. Analyze the current protocol, request a live run, and confirm the device, revision, and physical deck in the workbench. This approval covers the run and LabscriptAI automatic recovery for supported minor faults. Pause and resume require confirmation. Stop is available for a run owned by the current conversation. Read the original run status after a lost connection before sending further actions. The `MOSS web` workflow checks the build, types, experiment storage and preview resources, and web client boot. It does not deploy the site or operate a physical robot. The Windows installer job uses bounded model credentials to verify the installed workbench and both local robot simulations. diff --git a/internal/experiment/README.i18n.yaml b/internal/experiment/README.i18n.yaml index 2939be2ff5a..f0c2043b72a 100644 --- a/internal/experiment/README.i18n.yaml +++ b/internal/experiment/README.i18n.yaml @@ -9,8 +9,8 @@ en: 0ed09a3887f5793f zh: 751c1e95eb15436f /internal-experiment-storage/preview-components: - en: 7cad7f93de39c12c - zh: 3672094237841e16 + en: f1a59d901d38188c + zh: d92b2cb054a16292 /internal-experiment-storage/known-limitations: en: aa9ffe6c5947fe96 zh: efd1f266f9f1d178 diff --git a/internal/experiment/README.md b/internal/experiment/README.md index 6006fec7764..174bedf2849 100644 --- a/internal/experiment/README.md +++ b/internal/experiment/README.md @@ -55,6 +55,8 @@ Run the declaration and tool tests with `node --import tsx/esm --test internal/e `PreviewResources` rechecks the owner and current task before serving `animation`, `setup`, or manifest-listed downloads. The version-locked MCP adapter confines each plugin process's writes to a private directory. Interrupted invocations retain that directory because child-process termination is uncertain. See [MOSS setup](../../MOSS-LAB.md). +The experiment preset registers the pinned server's published MCP schemas and loads the plugin's experiment instructions. The adapter binds requests to the executing conversation and configured robot, keeps the plugin's conversation data across calls, and publishes returned camera images through the shared MCP attachment adapter. Physical actions outside an approved run require a device confirmation. LabscriptAI `runtime_watch` can send recovery actions even when passed `self_fix_mode=observe`, so the preset reserves that tool for an active run with recorded recovery approval. Read-only run status uses history or the recovery monitor with execution disabled. + A passed `protocol-analysis` check stores the full analysis bytes (`analysisBase64`) next to its SHA-256. `get_experiment` omits those bytes from its check results; they remain available internally for preview recovery. Published previews and per-session selection live only in process memory; when a session's status is polled after a restart and no preview is selected, the status route rebuilds the scene from the persisted analysis of the latest passed check for that session's newest experiment, verifies its digest, and reports `checking` until the rebuild finishes. Each process attempts recovery at most once per completed check; polling before a check passes does not consume that attempt. A stored check recorded before analysis persistence began cannot recover. The authenticated `/api/robot-status` route reads `OPENTRONS_URL` at startup and queries only the robot's health and instruments endpoints on demand. It returns available model, health status, instruments and query time; an unconfigured, unreachable or partially responding robot is reported separately. This snapshot is not a device-readiness or safety assessment. diff --git a/internal/experiment/README.zh.md b/internal/experiment/README.zh.md index 091e90e1535..090499bf203 100644 --- a/internal/experiment/README.zh.md +++ b/internal/experiment/README.zh.md @@ -55,6 +55,8 @@ Agent 工具要求完整 Python 源码。可选的 `parameters.initialVolumeUl` `PreviewResources` 在提供 `animation`、`setup` 或清单内的下载文件前,核对归属和当前任务。锁定版本的 MCP 适配器将每次插件调用的写入限制在私有目录内。调用中断后保留该目录,因为无法确认子进程已经退出。见 [MOSS 安装](../../MOSS-LAB.md)。 +实验助手预设注册固定版本服务公开的 MCP 工具定义,并加载插件的实验指引。适配器绑定当前会话和已配置的机器人,跨调用保留插件会话数据,并通过通用 MCP 附件适配器提供拍摄的图片。已批准运行范围以外的真机操作需要设备确认。LabscriptAI 的 `runtime_watch` 即使收到 `self_fix_mode=observe` 也可能发送恢复动作,因此预设只允许它监看已记录恢复授权的活动运行。只读查询可使用运行历史,或使用禁用执行的恢复监控。 + 通过的 `protocol-analysis` 检查在 SHA-256 之外保存完整分析数据(`analysisBase64`)。`get_experiment` 的检查结果不返回这些数据;内部仍可使用它们恢复预览。已发布预览和会话内选择仅保存在进程内存中;重启后轮询某会话状态且没有已选预览时,状态路由会用该会话最新实验的最新通过检查所保存的分析数据重建场景,校验其摘要,并在重建完成前返回 `checking`。每个进程对每项已完成检查最多尝试一次恢复;检查通过前的轮询不会消耗这次尝试。分析持久化开始之前记录的检查无法恢复。 认证路由 `/api/robot-status` 在启动时读取 `OPENTRONS_URL`,仅在用户请求时查询机器人的健康及移液器接口。结果包含可用的型号、健康状态、移液器和查询时间;未配置、不可达或部分响应分别报告。此快照不代表设备已就绪或实验安全。 diff --git a/internal/experiment/labscriptai-tools.mjs b/internal/experiment/labscriptai-tools.mjs new file mode 100644 index 00000000000..c0d0ccd77dd --- /dev/null +++ b/internal/experiment/labscriptai-tools.mjs @@ -0,0 +1,160 @@ +/** Discover the pinned MCP tools in the experiment assistant's registration scope. */ +import { createMcpToolDefinition } from '@deepseek-ai/dsh-mcp-client' +import { defineTool } from '@deepseek-ai/dsh-tools' +import { ExperimentError } from './index.mjs' +import { approveRobotAction, startOwnedRobotRun } from './robot-tools.mjs' + +export const name = 'labscriptai-tools' +export const inject = ['tools', 'systemPrompt', 'experimentStore', 'labscriptaiRuntime', 'robotControl'] + +const localTools = new Set([ + 'labware_lookup', 'estimate_tip_budget', 'record_liquid_source_map', 'apply_liquid_probe_results', 'liquid_source_map', + 'validate_virtual_lab_state_steps', 'list_recovery_playbooks', 'runtime_alerts', 'runtime_recovery_self_test', + 'liquid_source_substitution', + 'simulate_protocol', 'protocol_artifacts', 'logicpass_check', 'flex3d_preflight_check', 'flex3d_open_viewer', +]) +const robotQueryTools = new Set([ + 'robot_status', 'get_protocols', 'deck_slots', 'tip_wells', 'is_home_safe', 'reconcile_state', 'suggest_recovery_action', + 'data_files', 'live_readiness_check', 'preflight_run_setup', 'parse_error', + 'live_liquid_recovery_gate', 'generate_continuation_protocol', +]) +const deviceActionTools = new Set([ + 'load_pipette', 'load_labware', 'load_module', 'control_module', 'move_labware', 'cleanup_motion', 'drop_attached_tip', + 'execute_protocol_recovery', 'recover_tip_pickup', +]) +const guidanceTopics = ['workflows', 'error-response', 'safety-policy'] + +function operation(name, args) { + switch (name) { + case 'runtime_outbox': return args.action === 'deliver' ? 'unconfigured' : 'local' + case 'camera_settings': return args.action === 'status' ? 'robot' : 'approve' + case 'capture_image': return args.mode === 'preview' ? 'robot' : 'approve' + case 'deck_vision_check': return args.mode === 'local' ? 'local' : 'robot' + case 'robot_authoring_context': return args.refresh === true ? 'robot' : 'optional_robot' + case 'safe_next_action': return 'optional_robot' + case 'health_check': return args.scope === 'robot' ? 'robot' : 'optional_robot' + case 'probe_wells': return args.execute_on_robot === true ? 'approve' : 'optional_robot' + case 'query_history': return args.scope === 'experiment_logs' ? 'local' : 'robot' + case 'runtime_watch': return 'watch' + case 'runtime_recovery_monitor': return 'monitor' + case 'run_protocol': return 'start' + case 'control_run': return 'control' + default: + if (localTools.has(name)) return 'local' + if (robotQueryTools.has(name)) return 'robot' + if (deviceActionTools.has(name)) return 'approve' + return 'unconfigured' + } +} + +function response(value) { + return { content: [{ type: 'text', text: JSON.stringify(value) }] } +} + +function requireActiveRun(control, sessionId, runId) { + const row = control.activeRunForMcp(sessionId, runId) + if (row.cancel_requested) throw new ExperimentError('ROBOT_RUN_INACTIVE', 'This run has a pending stop request.') + return row +} + +function sameProtocol(store, sessionId, row) { + return store.getForSession(sessionId, row.experiment_id, row.revision).snapshot.protocol +} + +function checkRequestedRobot(address, target) { + if (address === undefined || address === target?.origin) return + throw new ExperimentError('ROBOT_TARGET_CHANGED', 'Use the configured robot address or omit robot_ip.') +} + +async function invoke(ctx, tool, args, exec) { + const sessionId = exec.agent.session.id + const runtime = ctx.labscriptaiRuntime + const control = ctx.robotControl + const store = ctx.experimentStore + const kind = operation(tool, args) + if (kind === 'unconfigured') throw new ExperimentError('PLUGIN_OPERATION_UNCONFIGURED', 'This LabscriptAI operation has no workbench policy.') + const target = kind === 'local' ? null : control.target() + checkRequestedRobot(args.robot_ip, target) + if (kind === 'start') { + const experiment = store.latestForSession(sessionId) + if (!experiment || args.file_path !== 'current_protocol.py' || args.auto_play === false || args.skip_logicpass_gate || args.skip_preflight || args.skip_preflight_deck_diff) { + throw new ExperimentError('PLUGIN_ARGUMENT_INVALID', 'Use current_protocol.py for the saved, analyzed experiment and request a normal run.') + } + const result = await startOwnedRobotRun(ctx, { experimentId: experiment.id, revision: experiment.revision }, exec) + return response({ ...result, run_id: result.runId ?? null }) + } + if (kind === 'control') { + const row = control.activeRunForMcp(sessionId, args.run_id) + const action = args.action === 'play' ? 'resume' : args.action + if (!['pause', 'resume', 'stop'].includes(action)) throw new ExperimentError('PLUGIN_ARGUMENT_INVALID', 'Use pause, play, or stop for this run.') + const intent = action === 'stop' ? null : ctx.get('mossVoiceIntent')?.captureIntent(sessionId) + if (action !== 'stop') await approveRobotAction(ctx, exec, `Confirm ${action} for robot run ${args.run_id}.`, `确认在机器人上${action === 'pause' ? '暂停' : '继续'}运行 ${args.run_id}?`) + return response(await control.controlRun({ sessionId, id: row.id, action, signal: exec.signal, approved: row.id, intent })) + } + if (kind !== 'local' && kind !== 'optional_robot' && !target) throw new ExperimentError('ROBOT_NOT_CONFIGURED', 'Configure the robot address first.') + if ((kind === 'approve' || kind === 'watch') && !control.allowLive) throw new ExperimentError('ROBOT_CONTROL_DISABLED', 'Live robot control is disabled.') + const forwarded = { ...args, session_id: sessionId } + // The workbench selects the target and external communications for the process. + delete forwarded.robot_ip + if (target) forwarded.robot_ip = target.origin + if (tool === 'deck_vision_check' && args.mode === 'preflight') forwarded.vlm_provider = 'off' + let protocol = store.latestForSession(sessionId)?.snapshot.protocol + let beforeDispatch + if (kind === 'watch' || ['execute_protocol_recovery', 'recover_tip_pickup'].includes(tool)) { + const row = requireActiveRun(control, sessionId, args.run_id) + const device = await control.status() + if (device.serial !== row.robot_serial || device.robotType !== row.robot_type) { + throw new ExperimentError('ROBOT_TARGET_CHANGED', 'The configured robot does not match the original run.') + } + protocol = sameProtocol(store, sessionId, row) + delete forwarded.file_path + delete forwarded.protocol_path + forwarded.protocol_source = protocol + beforeDispatch = () => { requireActiveRun(control, sessionId, row.robot_run_id) } + if (kind === 'watch') { + if (!(await runtime.recoveryGranted(row.id))) throw new ExperimentError('ROBOT_RECOVERY_NOT_APPROVED', 'This run has no automatic recovery approval. Use query_history to check it.') + Object.assign(forwarded, { self_fix_mode: 'l0', allow_l4_execution: true, operator_opt_in: true }) + } + } + if (kind === 'monitor') { + forwarded.self_fix_mode = 'observe' + forwarded.allow_l4_execution = false + forwarded.operator_opt_in = false + } + if (kind === 'approve') { + const { serial } = await control.status() + if (!serial) throw new ExperimentError('ROBOT_NOT_READY', 'The device identity could not be verified.') + const intent = ctx.get('mossVoiceIntent')?.captureIntent(sessionId) + await approveRobotAction(ctx, exec, `Allow ${tool} on robot ${serial}? Review the requested action and stay at the robot.`, + `允许在机器人 ${serial} 上执行 ${tool}?请核对操作并留在设备旁。`) + if ((await control.status()).serial !== serial) throw new ExperimentError('ROBOT_TARGET_CHANGED', 'The configured robot changed. Review the device again.') + const verifyRun = beforeDispatch + beforeDispatch = () => { intent?.assertCurrent(); verifyRun?.() } + } + const dispatch = signal => runtime.experiment(target, tool, forwarded, { sessionId, signal, protocol, beforeDispatch }) + return kind === 'watch' ? control.watchRun(sessionId, forwarded.run_id, exec.signal, dispatch) : dispatch(exec.signal) +} + +/** Expose the upstream schemas, original guidance, and session-owned dispatch. */ +export async function apply(ctx, config) { + if (typeof config?.prefix !== 'string' || !config.prefix.trim()) throw new Error('LabscriptAI tools require experiment assistant instructions.') + const [workflow, tools] = await Promise.all([ctx.labscriptaiRuntime.workflow(), ctx.labscriptaiRuntime.catalog()]) + const definitions = tools.map(tool => createMcpToolDefinition(ctx, { + name: `mcp__labscriptai__${tool.name}`, rawName: tool.name, description: tool.description ?? '', + inputSchema: tool.inputSchema, outputSchema: tool.outputSchema, taskRequired: tool.execution?.taskSupport === 'required', + call: (args, exec) => invoke(ctx, tool.name, args, exec), + })) + definitions.push(defineTool({ + name: 'read_labscriptai_guidance', + description: 'Read the pinned LabscriptAI workflow, recovery rules, or operating policy when the experiment needs that detail.', + parameters: { topic: { type: 'string', enum: guidanceTopics, required: true } }, + output: { schema: { type: 'string' }, render: (_args, text) => [{ type: 'text', text }] }, + execute: ({ topic }) => ctx.labscriptaiRuntime.guidance(topic), + })) + for (const definition of definitions) ctx.effect(() => ctx.tools.register(definition), `labscriptai.${definition.name}`) + ctx.effect(() => ctx.systemPrompt.suppressRuntimeContext(), 'labscriptai.runtime-context') + ctx.effect(() => ctx.systemPrompt.section({ + name: 'labscriptai:experiment-assistant', order: 0, complete: true, interpolate: false, + text: `${config.prefix}\n\n${workflow}`, + }), 'labscriptai.experiment-assistant') +} diff --git a/internal/experiment/plugin-client.mjs b/internal/experiment/plugin-client.mjs index 5c802dd88e8..695e2fb0950 100644 --- a/internal/experiment/plugin-client.mjs +++ b/internal/experiment/plugin-client.mjs @@ -3,7 +3,7 @@ import { Client } from '@modelcontextprotocol/client' import { StdioClientTransport } from '@modelcontextprotocol/client/stdio' import { createHash } from 'node:crypto' import { mkdir, mkdtemp, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises' -import { isAbsolute, join, relative } from 'node:path' +import { isAbsolute, join, relative, resolve, dirname, basename } from 'node:path' import { ExperimentError } from './index.mjs' const digest = bytes => createHash('sha256').update(bytes).digest('hex') @@ -34,6 +34,58 @@ async function writeProtocol(directory, protocol) { return path } +function within(directory, path) { + const rel = relative(directory, path) + return !isAbsolute(rel) && rel !== '..' && !rel.startsWith('../') && !rel.startsWith('..\\') +} + +async function prepareExperimentArguments(workspace, directory, name, args, protocol) { + const input = { ...args } + let protocolPath + for (const [key, value] of Object.entries(input)) { + if (key === 'weights' || key === 'python_executable' || key === 'base_url' || key === 'api_key' + || key === 'webhook_url' || key === 'notify_adapters' || key === 'watch_dir' || key === 'outbox_dir') { + throw new ExperimentError('PLUGIN_ARGUMENT_FORBIDDEN', `LabscriptAI setting ${key} is managed by the workbench.`) + } + if (!/(?:_path|_dir|_file|_folder)$/.test(key) && !(key === 'source' && name === 'flex3d_preflight_check')) continue + if (typeof value !== 'string' || !value) throw new ExperimentError('PLUGIN_ARGUMENT_INVALID', `Invalid LabscriptAI path for ${key}.`) + if (value === 'current_protocol.py' && protocol && ['file_path', 'protocol_path', 'source'].includes(key)) { + protocolPath ??= await writeProtocol(directory, protocol) + input[key] = protocolPath + continue + } + const canonicalRoot = await realpath(workspace) + const path = resolve(canonicalRoot, value) + if (!within(canonicalRoot, path)) throw new ExperimentError('PLUGIN_ARGUMENT_FORBIDDEN', `The ${key} path must belong to this experiment session.`) + let canonical + try { canonical = await realpath(path) } catch (error) { + if (error.code !== 'ENOENT') throw error + canonical = join(await realpath(dirname(path)), basename(path)) + } + if (!within(canonicalRoot, canonical)) throw new ExperimentError('PLUGIN_ARGUMENT_FORBIDDEN', `The ${key} path must belong to this experiment session.`) + input[key] = canonical + } + return input +} + +async function photoResult(workspace, response) { + const json = response.content.find(item => item.type === 'text')?.text + if (!json || response.isError) return response + const envelope = JSON.parse(json) + if (envelope.success !== true) return response + const data = envelope.data + const content = [...response.content] + for (const path of new Set([data?.saved_to, data?.image_path, data?.annotated_image_path, data?.yolo?.annotated_image_path])) { + if (typeof path !== 'string') continue + const bytes = await readPluginFile(workspace, path, 12 * 1024 * 1024) + const mimeType = bytes.subarray(0, 3).equals(Buffer.from([255, 216, 255])) ? 'image/jpeg' + : bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) ? 'image/png' : undefined + if (!mimeType) throw new ExperimentError('PLUGIN_RESPONSE_INVALID', 'LabscriptAI returned an unsupported photo format.') + content.push({ type: 'image', data: bytes.toString('base64'), mimeType }) + } + return { ...response, content } +} + /** Create a confined MCP client for simulation, documents and configured robot operations. * @param {object} config Frozen plugin paths, version, timeout, and sandbox service. * @returns {object} Analysis, portable-document and robot methods; caller awaits operations before disposal. @@ -42,24 +94,40 @@ export function createPluginClient(config) { for (const key of ['root', 'data', 'dependencyHome', 'version']) { if (typeof config?.[key] !== 'string' || !config[key]) throw new Error(`LabscriptAI client requires ${key}`) } + if (config.state !== undefined && !isAbsolute(config.state)) throw new Error('LabscriptAI state requires an absolute directory.') + if (config.visionPython && !isAbsolute(config.visionPython)) throw new Error('MOSS_VISION_PYTHON requires an absolute interpreter path.') if (!Number.isSafeInteger(config.timeoutMs) || config.timeoutMs < 150000 || !config.sandbox) throw new Error('LabscriptAI client requires sandbox and timeoutMs >= 150000') - async function invoke(operation, robot, beforeDispatch) { - const directory = await mkdtemp(join(await realpath(config.data), 'mcp-')) + async function sessionDirectory(sessionId) { + const state = config.state ?? config.data + const directory = join(state, `session-${digest(sessionId)}`) + await mkdir(directory, { recursive: true, mode: 0o700 }) + if (await realpath(directory) !== join(await realpath(state), basename(directory))) { + throw new ExperimentError('PLUGIN_STATE_INVALID', 'The experiment tool data directory was replaced.') + } + return directory + } + + async function invoke(operation, robot, beforeDispatch, { sessionId, abort, vision = false } = {}) { + const workspace = sessionId === undefined ? undefined : await sessionDirectory(sessionId) + const directory = await mkdtemp(join(await realpath(workspace ?? config.data), 'mcp-')) const home = join(directory, 'home') await mkdir(home) - const timeoutMs = robot && !beforeDispatch ? Math.min(config.timeoutMs, 30000) : config.timeoutMs - const signal = AbortSignal.timeout(timeoutMs) + const timeoutMs = robot && !beforeDispatch && sessionId === undefined ? Math.min(config.timeoutMs, 30000) : config.timeoutMs + const deadline = AbortSignal.timeout(timeoutMs) + const signal = abort ? AbortSignal.any([abort, deadline]) : deadline let confined - try { confined = await config.sandbox.confine([process.execPath, join(config.root, 'servers/opentrons-mcp/index.js')], { mode: 'workspace-write', workspaceRoot: directory }, signal) } catch (error) { + try { confined = await config.sandbox.confine([process.execPath, join(config.root, 'servers/opentrons-mcp/index.js')], { mode: 'workspace-write', workspaceRoot: workspace ?? directory }, signal) } catch (error) { await rm(directory, { recursive: true, force: true }) throw error } const env = Object.fromEntries(['PATH', 'SystemRoot', 'ComSpec', 'LOCALAPPDATA', 'USERPROFILE'].filter(key => process.env[key]).map(key => [key, process.env[key]])) const transport = new StdioClientTransport({ command: confined.argv[0], args: confined.argv.slice(1), cwd: directory, stderr: 'pipe', env: { ...env, HOME: home, TMPDIR: directory, TEMP: directory, TMP: directory, PYTHONDONTWRITEBYTECODE: '1', - PLUGIN_DATA: directory, OPENTRONS_PLUGIN_ROOT: config.root, LABSCRIPTAI_HOME: config.dependencyHome, + PLUGIN_DATA: workspace ?? directory, OPENTRONS_PLUGIN_ROOT: config.root, LABSCRIPTAI_HOME: config.dependencyHome, LABSCRIPTAI_INHERIT_PRIVATE_ACL: process.platform === 'win32' ? '1' : '0', - FLEX3D_EXPORT: join(directory, 'export'), OPENTRONS_CONNECTION_FILE: join(directory, 'robot.json'), + FLEX3D_EXPORT: join(workspace ?? directory, 'export'), OPENTRONS_CONNECTION_FILE: join(workspace ?? directory, 'robot.json'), + ...(vision ? { OPENTRONS_PREFLIGHT_VISION: 'on', OPENTRONS_VLM_PROVIDER: 'off', + ...(config.visionPython ? { OPENTRONS_PYTHON: config.visionPython } : {}) } : {}), ...(robot ? { OPENTRONS_HOST: robot.origin, ...(robot.authorization ? { OPENTRONS_AUTHORIZATION: robot.authorization } : {}) } : {}), MUJOCO_GL: 'disable' }, maxBufferSize: 12 * 1024 * 1024, }) const client = new Client({ name: 'moss-lab-artifacts', version: '1' }) @@ -69,13 +137,16 @@ export function createPluginClient(config) { try { await client.connect(transport, { signal, timeout: timeoutMs }) if (client.getServerVersion()?.version !== config.version) throw new ExperimentError('PLUGIN_VERSION_MISMATCH', 'plugin version differs from the lock; rerun installation') - const call = async (name, args) => { - const allowed = robot ? ['robot_status', 'get_protocols', 'query_history', 'run_protocol', 'preflight_run_setup', 'control_run'] : ['simulate_protocol', 'protocol_artifacts'] - if (!allowed.includes(name)) throw new Error('MCP operation is not allowed') + const dispatch = async (name, args) => { + signal.throwIfAborted() beforeDispatch?.() unsettled = true const response = await client.callTool({ name, arguments: args }, { signal, timeout: timeoutMs }) unsettled = false + return response + } + const call = async (name, args) => { + const response = await dispatch(name, args) const text = response.content?.find(item => item.type === 'text')?.text let envelope try { envelope = JSON.parse(text) } catch (error) { throw new ExperimentError('PLUGIN_RESPONSE_INVALID', 'plugin returned unreadable JSON', { cause: error.message }) } @@ -87,9 +158,12 @@ export function createPluginClient(config) { } return envelope.data } - return await operation(call, directory) + return await operation(call, directory, { dispatch, client, signal, timeoutMs, workspace }) } catch (error) { if (error instanceof ExperimentError) throw error + if (unsettled && robot && beforeDispatch) { + throw new ExperimentError('ROBOT_ACTION_UNCONFIRMED', 'LabscriptAI did not confirm the robot operation. Read the original run or device status before sending another action.', { cause: error.message }) + } throw new ExperimentError('PLUGIN_CALL_FAILED', 'LabscriptAI operation failed; check the installed version and retry', { diagnostic, cause: error.message }) } finally { await client.close() @@ -100,11 +174,48 @@ export function createPluginClient(config) { } } return { - robot(robot, name, args, protocol, beforeDispatch) { + async catalog() { + return invoke(async (_call, _directory, { client, signal, timeoutMs }) => { + const { tools } = await client.listTools(undefined, { signal, timeout: timeoutMs }) + if (!tools.length) throw new ExperimentError('PLUGIN_RESPONSE_INVALID', 'LabscriptAI did not publish any tools.') + return tools + }) + }, + workflow: () => readPluginFile(config.root, join(config.root, 'skills/opentrons-experiment-run/SKILL.md'), 64 * 1024).then(bytes => bytes.toString('utf8')), + guidance: topic => readPluginFile(config.root, join(config.root, 'policy', `${topic}.md`), 64 * 1024).then(bytes => bytes.toString('utf8')), + async grantRecovery(id) { + const directory = join(config.state ?? config.data, 'run-approvals') + await mkdir(directory, { recursive: true, mode: 0o700 }) + await writeFile(join(directory, digest(id)), 'automatic recovery\n', { mode: 0o600, flag: 'wx' }) + }, + async recoveryGranted(id) { + try { + return (await readFile(join(config.state ?? config.data, 'run-approvals', digest(id)), 'utf8')) === 'automatic recovery\n' + } catch (error) { + if (error.code !== 'ENOENT') throw error + return false + } + }, + experiment(robot, name, args, { sessionId, signal, protocol, beforeDispatch }) { + return invoke(async (_call, directory, { dispatch, workspace }) => { + const input = await prepareExperimentArguments(workspace, directory, name, args, protocol) + if (name === 'runtime_watch' && input.mode === 'loop') { + const limit = Math.floor(config.timeoutMs * 0.8) + input.max_runtime_ms ??= limit + if (input.max_runtime_ms > limit) { + throw new ExperimentError('PLUGIN_ARGUMENT_INVALID', `Use a watch loop of at most ${limit} ms and resume it while the run is active.`) + } + } + const response = await dispatch(name, input) + return name === 'capture_image' || name === 'deck_vision_check' ? photoResult(workspace, response) : response + }, robot, beforeDispatch, { sessionId, abort: signal, vision: name === 'deck_vision_check' }) + }, + robot(robot, name, args, protocol, beforeDispatch, sessionId) { + if (!['robot_status', 'get_protocols', 'query_history', 'run_protocol', 'preflight_run_setup', 'control_run'].includes(name)) throw new Error('Unknown MOSS robot operation.') return invoke(async (call, directory) => { if (protocol === undefined) return call(name, args) return call(name, { ...args, file_path: await writeProtocol(directory, protocol) }) - }, robot, beforeDispatch) + }, robot, beforeDispatch, { sessionId }) }, analyze(protocol) { return invoke(async (call, directory) => { diff --git a/internal/experiment/robot-control-plugin.mjs b/internal/experiment/robot-control-plugin.mjs index a8ea01e1d63..ed2405c945e 100644 --- a/internal/experiment/robot-control-plugin.mjs +++ b/internal/experiment/robot-control-plugin.mjs @@ -19,9 +19,10 @@ export function apply(ctx, config) { target = { origin: url.origin, authorization } } const store = ctx.experimentStore - const call = (tool, args, protocol, beforeDispatch) => { + const pendingWatches = new Map() + const call = (tool, args, protocol, beforeDispatch, sessionId) => { if (!target) throw new ExperimentError('ROBOT_NOT_CONFIGURED', 'Configure the robot address first.') - return ctx.labscriptaiRuntime.robot(target, tool, { ...args, robot_ip: target.origin }, protocol, beforeDispatch) + return ctx.labscriptaiRuntime.robot(target, tool, { ...args, ...(sessionId ? { session_id: sessionId } : {}), robot_ip: target.origin }, protocol, beforeDispatch, sessionId) } function requireLive() { if (!config.allowLive) throw new ExperimentError('ROBOT_CONTROL_DISABLED', 'Live robot control is disabled. Set MOSS_ALLOW_LIVE_ROBOT=1 to enable it.') @@ -42,13 +43,16 @@ export function apply(ctx, config) { } async function status() { - const value = await call('robot_status', { include_modules: false }) + const value = await call('robot_status', { include_modules: true }) return { robotType: value.authoring_context?.robot_type ?? null, serial: value.health_summary?.robot_serial ?? null, name: value.health_summary?.name ?? null, blockers: value.blockers ?? [], unchecked: value.not_checked ?? [], + authoringContext: value.authoring_context ?? null, + deckConfiguration: value.deck_configuration ?? null, + modules: value.modules?.modules ?? [], } } @@ -66,7 +70,7 @@ export function apply(ctx, config) { return call('control_run', { run_id: row.robot_run_id, action, return_after_action: true, ...identity(row), ...(expectedStatus ? { expected_run_status: expectedStatus } : {}), - }, undefined, beforeDispatch) + }, undefined, beforeDispatch, row.session_id) } async function reconcilePreparedRun(row) { @@ -131,9 +135,10 @@ export function apply(ctx, config) { } let physicalId = null try { + if (approved.automaticRecovery) await ctx.labscriptaiRuntime.grantRecovery(id) const result = await call('run_protocol', { key: id, auto_play: false, return_after_prepare: true, ...identity(row), - }, experiment.snapshot.protocol, beforePrepare) + }, experiment.snapshot.protocol, beforePrepare, sessionId) physicalId = result.created_run?.data?.id ?? result.created_run?.id if (!identifier(physicalId)) throw new ExperimentError('ROBOT_PREPARATION_INVALID', 'OT did not return a usable run ID.') store.recordRobotRun(sessionId, id, physicalId) @@ -168,10 +173,31 @@ export function apply(ctx, config) { } } + function activeRunForMcp(sessionId, runId) { + const id = target && store.activeRobotRun(sessionId, target.origin) + if (!id) throw new ExperimentError('ROBOT_RUN_NOT_FOUND', 'There is no active robot run in this conversation.') + const row = run(sessionId, id) + if (!row.robot_run_id || row.robot_run_id !== runId) throw new ExperimentError('ROBOT_RUN_NOT_FOUND', 'This run does not belong to the active experiment.') + return row + } + + async function watchRun(sessionId, runId, signal, watch) { + const row = activeRunForMcp(sessionId, runId) + if (row.cancel_requested || pendingWatches.has(row.id)) throw new ExperimentError('ROBOT_WATCH_UNAVAILABLE', 'This run is stopping or already has a watcher.') + const controller = new AbortController() + pendingWatches.set(row.id, controller) + try { + return await watch(AbortSignal.any([signal, controller.signal])) + } finally { + pendingWatches.delete(row.id) + } + } + async function controlRun({ sessionId, id, action, signal, approved, intent }) { let row = run(sessionId, id) if (action === 'stop') { store.requestRobotStop(sessionId, id) + pendingWatches.get(id)?.abort() row = run(sessionId, id) if (row.active && !row.robot_run_id) { try { await reconcilePreparedRun(row) } catch { /* Cancellation is already durable. */ } @@ -202,9 +228,13 @@ export function apply(ctx, config) { } } - ctx.effect(() => ctx.provide('robotControl', { - configured: target !== null, allowLive: config.allowLive, - verifyStart, status, startRun, getRun, controlRun, - activeRun: sessionId => target ? store.activeRobotRun(sessionId, target.origin) : null, - }), 'robot-control.service') + ctx.effect(() => { + ctx.provide('robotControl', { + configured: target !== null, allowLive: config.allowLive, + verifyStart, status, startRun, getRun, controlRun, activeRunForMcp, watchRun, + target: () => target, + activeRun: sessionId => target ? store.activeRobotRun(sessionId, target.origin) : null, + }) + return () => { for (const watcher of pendingWatches.values()) watcher.abort() } + }, 'robot-control.service') } diff --git a/internal/experiment/robot-tools.mjs b/internal/experiment/robot-tools.mjs index 6a2a568928f..e3283f13051 100644 --- a/internal/experiment/robot-tools.mjs +++ b/internal/experiment/robot-tools.mjs @@ -13,17 +13,31 @@ function sessionId(exec) { return id } -async function approve(ctx, exec, en, zh) { +/** Ask the workbench for a one-shot device decision independent of file access. */ +export async function approveRobotAction(ctx, exec, en, zh) { const approval = ctx.get('approval') if (!approval) throw new Error('Open the MOSS workbench to confirm physical robot operations.') const outcome = await approval.request({ agent: exec.agent, toolName: exec.name, callId: exec.callId, reason: en, displayReason: { en, zh }, signal: exec.signal, - }) + }, { policy: 'ask' }) if (outcome !== 'allowed-once') throw new Error('The operator did not approve this robot action.') exec.signal.throwIfAborted() } +/** Start the saved revision through the device confirmation and run receipt. */ +export async function startOwnedRobotRun(ctx, args, exec) { + const control = ctx.robotControl + const session = sessionId(exec) + const intent = ctx.get('mossVoiceIntent')?.captureIntent(session) + const { robot, analysis } = await control.verifyStart(session, args.experimentId, args.revision) + intent?.assertCurrent() + await approveRobotAction(ctx, exec, + `Run experiment ${args.experimentId} revision ${args.revision} on ${robot.robotType} (${robot.serial})? This includes LabscriptAI automatic recovery for supported minor issues. Confirm the physical deck and stay at the robot.`, + `在 ${robot.robotType}(${robot.serial})运行实验 ${args.experimentId} 的第 ${args.revision} 版?本次运行允许 LabscriptAI 自动处理它支持的小故障。请核对台面并留在设备旁。`) + return control.startRun({ ...args, sessionId: session, signal: exec.signal, approved: { ...robot, taskId: analysis.taskId, intent, automaticRecovery: true } }) +} + /** Expose physical robot operations in the experiment assistant preset. */ export function apply(ctx) { const control = ctx.robotControl @@ -40,16 +54,7 @@ export function apply(ctx) { description: 'Run the analyzed experiment on the physical robot only when explicitly requested. The workbench requests operator approval for the exact device and protocol revision. The acknowledgement does not establish completion.', parameters: { experimentId, revision }, output, - async execute(args, exec) { - const session = sessionId(exec) - const intent = ctx.get('mossVoiceIntent')?.captureIntent(session) - const { robot, analysis } = await control.verifyStart(session, args.experimentId, args.revision) - intent?.assertCurrent() - await approve(ctx, exec, - `Run experiment ${args.experimentId} revision ${args.revision} on ${robot.robotType} (${robot.serial})? Confirm the physical deck and stay at the robot.`, - `在 ${robot.robotType}(${robot.serial})运行实验 ${args.experimentId} 的第 ${args.revision} 版?请核对实体台面并留在设备旁。`) - return control.startRun({ ...args, sessionId: session, signal: exec.signal, approved: { ...robot, taskId: analysis.taskId, intent } }) - }, + execute: (args, exec) => startOwnedRobotRun(ctx, args, exec), })), 'robot-tools.start') ctx.effect(() => ctx.tools.register(defineTool({ @@ -74,7 +79,7 @@ export function apply(ctx) { const intent = args.action === 'stop' ? null : ctx.get('mossVoiceIntent')?.captureIntent(session) if (args.action !== 'stop') { if (!control.allowLive) throw new Error('Live robot control is disabled.') - await approve(ctx, exec, `Confirm ${args.action} for robot run ${args.id}.`, + await approveRobotAction(ctx, exec, `Confirm ${args.action} for robot run ${args.id}.`, `确认${args.action === 'pause' ? '暂停' : '继续'}真机运行 ${args.id}?`) } return control.controlRun({ ...args, sessionId: session, signal: exec.signal, approved: args.id, intent }) diff --git a/internal/experiment/runtime-plugin.mjs b/internal/experiment/runtime-plugin.mjs index c9ba6fb86ec..c7e004a2817 100644 --- a/internal/experiment/runtime-plugin.mjs +++ b/internal/experiment/runtime-plugin.mjs @@ -9,12 +9,15 @@ export function apply(ctx, config) { const client = createPluginClient({ ...config, sandbox: ctx.sandbox }) const pending = new Set() let closing = false - const service = Object.fromEntries(['analyze', 'documents', 'robot'].map(method => [method, async (...args) => { + const service = Object.fromEntries(['analyze', 'documents', 'robot', 'catalog', 'workflow', 'guidance', 'experiment', 'grantRecovery', 'recoveryGranted'].map(method => [method, async (...args) => { if (closing) throw new Error('LabscriptAI runtime is closing') const operation = client[method](...args) pending.add(operation) try { return await operation } finally { pending.delete(operation) } }])) + const catalog = service.catalog + let discovery + service.catalog = () => discovery ??= catalog().catch(error => { discovery = undefined; throw error }) ctx.effect(() => { ctx.provide('labscriptaiRuntime', service) return async () => { closing = true; await Promise.allSettled([...pending]) } diff --git a/internal/experiment/tests/labscriptai-tools.test.mjs b/internal/experiment/tests/labscriptai-tools.test.mjs new file mode 100644 index 00000000000..676710eb204 --- /dev/null +++ b/internal/experiment/tests/labscriptai-tools.test.mjs @@ -0,0 +1,131 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createPluginClient } from '../plugin-client.mjs' +import { apply } from '../labscriptai-tools.mjs' + +const schema = { type: 'object', properties: {} } +const target = { origin: 'http://127.0.0.1:31950' } +const row = { id: 'receipt', robot_run_id: 'physical', robot_serial: 'Flex-1', robot_type: 'Flex', experiment_id: 'experiment', revision: 1 } +const experiment = { id: row.experiment_id, revision: row.revision, snapshot: { protocol: 'owned protocol' } } + +test('discovers tools, scopes calls, and reuses only the approved run for automatic recovery', async () => { + const calls = [] + const tools = new Map() + const sections = [] + const approvals = [] + let granted = false + let cancelled = false + const ctx = { + get(key) { if (key === 'approval') return { async request(request, options) { approvals.push({ request, options }); return 'allowed-once' } } }, + effect(fn) { fn() }, + tools: { register(tool) { tools.set(tool.name, tool) } }, + systemPrompt: { suppressRuntimeContext() {}, section(section) { sections.push(section) } }, + experimentStore: { latestForSession: () => experiment, getForSession: () => experiment }, + labscriptaiRuntime: { + catalog: async () => ['robot_status', 'run_protocol', 'runtime_watch', 'runtime_recovery_monitor', 'capture_image', 'deck_vision_check', 'new_operation'].map(name => ({ name, inputSchema: schema })), + workflow: async () => 'upstream workflow', + recoveryGranted: async id => granted && id === row.id, + experiment(robot, name, args, options) { + options.beforeDispatch?.() + calls.push({ robot, name, args, options }) + return { content: [{ type: 'text', text: 'ok' }] } + }, + }, + robotControl: { + target: () => target, allowLive: true, + status: async () => ({ serial: row.robot_serial, robotType: row.robot_type }), + watchRun: (_sessionId, _runId, signal, watch) => watch(signal), + activeRunForMcp(sessionId, runId) { + assert.equal(sessionId, 'owner') + assert.equal(runId, row.robot_run_id) + return { ...row, cancel_requested: cancelled } + }, + verifyStart: async () => ({ robot: { serial: 'Flex-1', robotType: 'Flex' }, analysis: { taskId: 'analysis' } }), + startRun: async input => { + assert.equal(input.sessionId, 'owner') + assert.equal(input.approved.automaticRecovery, true) + granted = true + return { runId: row.robot_run_id, status: 'start_acknowledged' } + }, + }, + } + await apply(ctx, { prefix: 'host' }) + assert.equal(sections[0].text, 'host\n\nupstream workflow') + const exec = { agent: { session: { id: 'owner' } }, name: 'tool', signal: new AbortController().signal } + const call = (name, args, invocation = exec) => tools.get(`mcp__labscriptai__${name}`).execute(args, { ...invocation }) + await assert.rejects(call('robot_status', { robot_ip: 'https://other.invalid' }), { code: 'ROBOT_TARGET_CHANGED' }) + await call('robot_status', { session_id: 'other', include_modules: true }) + assert.deepEqual(calls[0].args, { robot_ip: target.origin, session_id: 'owner', include_modules: true }) + await call('capture_image', { mode: 'preview' }) + await call('deck_vision_check', { mode: 'local' }) + assert.equal(calls[1].robot, target) + assert.equal(calls[2].robot, null) + assert.equal(approvals.length, 0) + await assert.rejects(call('new_operation', {}), { code: 'PLUGIN_OPERATION_UNCONFIGURED' }) + const watch = { mode: 'poll', run_id: row.robot_run_id, protocol_source: 'untrusted' } + await assert.rejects(call('runtime_watch', watch), { code: 'ROBOT_RECOVERY_NOT_APPROVED' }) + await call('runtime_recovery_monitor', { run_id: row.robot_run_id, operator_opt_in: true, self_fix_mode: 'l0', allow_l4_execution: true }) + assert.equal(calls.at(-1).args.operator_opt_in, false) + assert.equal(calls.at(-1).args.self_fix_mode, 'observe') + const result = await call('run_protocol', { file_path: 'current_protocol.py' }) + assert.equal(JSON.parse(result.content[0].text).run_id, row.robot_run_id) + assert.equal(approvals[0].options.policy, 'ask') + assert.match(approvals[0].request.reason, /automatic recovery/) + await call('runtime_watch', watch) + assert.equal(calls.at(-1).args.protocol_source, 'owned protocol') + assert.equal(calls.at(-1).args.operator_opt_in, true) + await assert.rejects(call('runtime_watch', { ...watch, run_id: 'other' })) + await assert.rejects(call('runtime_watch', watch, { ...exec, agent: { session: { id: 'other' } } })) + cancelled = true + await assert.rejects(call('runtime_watch', watch), { code: 'ROBOT_RUN_INACTIVE' }) +}) + +test('discovers the stdio catalog and preserves plugin photos only within the owning session', async t => { + const root = await mkdtemp(join(tmpdir(), 'moss-mcp-discovery-')) + t.after(() => rm(root, { recursive: true, force: true })) + const server = join(root, 'servers', 'opentrons-mcp') + await mkdir(server, { recursive: true }) + await writeFile(join(server, 'index.js'), ` +const { createInterface } = require('node:readline') +const { writeFileSync } = require('node:fs') +const { join } = require('node:path') +const tool = name => ({ name, inputSchema: { type: 'object' } }) +createInterface({ input: process.stdin }).on('line', line => { + const request = JSON.parse(line) + if (request.id === undefined) return + let result + if (request.method === 'initialize') result = { protocolVersion: '2025-03-26', capabilities: { tools: {} }, serverInfo: { name: 'test-labscriptai', version: '0.1.5' } } + if (request.method === 'tools/list') result = request.params?.cursor ? { tools: [tool('deck_vision_check')] } : { tools: [tool('capture_image')], nextCursor: 'next' } + if (request.method === 'tools/call') { + const input = request.params.arguments + let data + if (request.params.name === 'deck_vision_check') { + data = { image_path: input.image_path, python: process.env.OPENTRONS_PYTHON } + } else { + const saved_to = input.output_path ?? join(process.env.PLUGIN_DATA, 'photo.jpg') + writeFileSync(saved_to, Buffer.from([255, 216, 255, 1])) + data = { saved_to } + } + result = { content: [{ type: 'text', text: JSON.stringify({ success: true, data }) }] } + } + process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }) + '\\n') +}) +`) + const runtime = createPluginClient({ root, data: root, state: join(root, 'state'), dependencyHome: root, version: '0.1.5', timeoutMs: 150000, visionPython: process.execPath, + sandbox: { async confine(argv) { return { argv } } } }) + assert.deepEqual((await runtime.catalog()).map(tool => tool.name), ['capture_image', 'deck_vision_check']) + const first = await runtime.experiment(target, 'capture_image', { mode: 'preview' }, { sessionId: 'first' }) + assert.deepEqual(first.content[1], { type: 'image', mimeType: 'image/jpeg', data: '/9j/AQ==' }) + const { saved_to } = JSON.parse(first.content[0].text).data + await assert.rejects(runtime.experiment(target, 'capture_image', { output_path: saved_to }, { sessionId: 'second' }), { code: 'PLUGIN_ARGUMENT_FORBIDDEN' }) + const reused = await runtime.experiment(null, 'deck_vision_check', { mode: 'local', image_path: saved_to }, { sessionId: 'first' }) + assert.equal(JSON.parse(reused.content[0].text).data.python, process.execPath) + assert.equal(reused.content[1].type, 'image') + assert.equal(await runtime.recoveryGranted('receipt'), false) + await runtime.grantRecovery('receipt') + assert.equal(await runtime.recoveryGranted('receipt'), true) + assert.equal(await runtime.recoveryGranted('other-receipt'), false) +}) diff --git a/internal/experiment/tests/robot-control.test.mjs b/internal/experiment/tests/robot-control.test.mjs index 05a4a52b250..3f229d801ef 100644 --- a/internal/experiment/tests/robot-control.test.mjs +++ b/internal/experiment/tests/robot-control.test.mjs @@ -27,14 +27,14 @@ function setup(t, model, allowLive = true) { const ctx = { experimentStore: store, effect(fn) { fn() }, provide(_, service) { control = service }, get(name) { - if (name === 'approval') return { async request(request) { state.request = request; return typeof state.approval === 'function' ? state.approval() : state.approval } } + if (name === 'approval') return { async request(request, options) { state.request = request; state.approvalPolicy = options?.policy; return typeof state.approval === 'function' ? state.approval() : state.approval } } if (name === 'mossVoiceIntent') return { captureIntent() { const captured = intent return { assertCurrent() { if (intent !== captured) throw new Error('superseded') } } } } }, tools: { register(tool) { tools[tool.name] = tool } }, - labscriptaiRuntime: { async robot(target, name, args, source, beforeDispatch) { + labscriptaiRuntime: { async grantRecovery(id) { state.recoveryApproved = id }, async robot(target, name, args, source, beforeDispatch) { assert.equal(target.origin, 'http://127.0.0.1:31950') assert.equal(args.robot_ip, target.origin) if (name === 'control_run' && args.action === 'play') state.beforePlay() @@ -78,6 +78,8 @@ for (const model of ['Flex', 'OT-2']) { f.state.approval = 'rejected' await assert.rejects(f.tools.start_robot_run.execute(f.input, f.exec), /did not approve/) assert.ok(f.calls.every(call => call.name === 'robot_status')) + assert.equal(f.state.recoveryApproved, undefined) + assert.equal(f.state.approvalPolicy, 'ask') f.state.approval = 'allowed-once' const run = await f.tools.start_robot_run.execute(f.input, f.exec) assert.match(f.state.request.displayReason.en, new RegExp(model)) @@ -97,6 +99,20 @@ for (const model of ['Flex', 'OT-2']) { }) } +test('stopping the run cancels its automatic recovery watcher', async t => { + const f = setup(t, 'Flex') + const result = await f.tools.start_robot_run.execute(f.input, f.exec) + const started = Promise.withResolvers() + const watcher = f.control.watchRun(f.input.sessionId, result.runId, f.exec.signal, signal => { + started.resolve() + return new Promise(resolve => signal.addEventListener('abort', () => resolve(signal.aborted), { once: true })) + }) + await started.promise + await assert.rejects(f.control.watchRun(f.input.sessionId, result.runId, f.exec.signal, () => {}), { code: 'ROBOT_WATCH_UNAVAILABLE' }) + assert.equal((await f.control.controlRun({ sessionId: f.input.sessionId, id: result.id, action: 'stop' })).status, 'action_acknowledged') + assert.equal(await watcher, true) +}) + test('mismatched devices and superseded intents do not play a protocol', async t => { const f = setup(t, 'Flex') f.state.model = 'OT-2' diff --git a/internal/xiaozhi/README.i18n.yaml b/internal/xiaozhi/README.i18n.yaml index cb087ac8293..0c5af7f2dfe 100644 --- a/internal/xiaozhi/README.i18n.yaml +++ b/internal/xiaozhi/README.i18n.yaml @@ -3,5 +3,5 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write internal/xiaozhi/README.md /xiaozhi-mcp-bridge: - en: e0dc331c291c6784 - zh: 295748c0f23f4267 + en: 8111d1a42982b072 + zh: 970760fa5a51f5fa diff --git a/internal/xiaozhi/README.md b/internal/xiaozhi/README.md index 64192ddd298..600b6bb5f00 100644 --- a/internal/xiaozhi/README.md +++ b/internal/xiaozhi/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) The local MOSS launch configuration mounts this Cordis plugin alongside the existing Web Agent. When `XIAOZHI_WSS_URL` is set, it opens one outbound secure WebSocket and exposes MCP tools. The address is a credential and is never logged. Without an endpoint the authenticated local workbench remains available. The socket reconnects with capped exponential backoff and WebSocket ping/pong checks. Reconnection re-registers tools without resubmitting accepted Agent turns; job receipts remain in memory only. -Voice delegation uses the `moss-experiment` preset named **实验助手**, with a laboratory persona and the experiment tools, including `request_experiment_input` for missing essential conditions. It does not mount the coding preset, shell, or repository-engineering instructions. +Voice delegation uses the `moss-experiment` preset named **实验助手**. Voice and Web messages in the same conversation share the LabscriptAI tools, experiment instructions, and workbench confirmation. The assistant can ask for missing details through `request_experiment_input`. `moss_delegate(message, newExperiment=false)` forwards the user's words to the active experiment conversation. Supplementary conditions and parameter changes reuse that conversation; only an explicit new experiment creates another. Do not supply a session ID from the model. The deployment can choose an initial session with `sessionId`, otherwise the first request creates one in the existing workspace, or in the configured `workspacePath` when no workspace exists. The private `bindingPath` file records the active identity and navigation sequence using an atomic replacement. A subsequent message after restart uses that identity; a missing conversation or a saved coding preset is reported rather than silently replaced. Explicitly start a new experiment to adopt the experiment preset while preserving the old conversation. diff --git a/internal/xiaozhi/README.zh.md b/internal/xiaozhi/README.zh.md index 78a2ee60e65..81084d70531 100644 --- a/internal/xiaozhi/README.zh.md +++ b/internal/xiaozhi/README.zh.md @@ -4,7 +4,7 @@ 本地 MOSS 启动配置把此 Cordis 插件与已有网页 Agent 一同挂载。配置 `XIAOZHI_WSS_URL` 时建立一条主动 WSS 连接并提供 MCP 工具;地址是凭据,不写入日志。不配置接入点时仍可使用认证后的本地工作台。连接断开后按有上限的指数退避重连,并用 WebSocket ping/pong 检查链路。重连会重新注册工具,不重发已接受的 Agent 任务;任务回执仍只保存在内存中。 -语音委派使用名为**实验助手**的 `moss-experiment` 预设,提供实验角色及实验工具,包括用于追问必要条件的 `request_experiment_input`,不载入通用编程模式、Shell 或仓库工程指令。 +语音委派使用名为**实验助手**的 `moss-experiment` 预设。同一会话中的语音和网页消息共用 LabscriptAI 工具、实验指引和工作台确认。助手可通过 `request_experiment_input` 追问缺失的实验条件。 `moss_delegate(message, newExperiment=false)` 把用户原话交给当前实验会话。补充条件和修改参数复用同一会话;只有明确的新实验才另建。模型不能传入会话 ID。部署者可通过 `sessionId` 指定初始会话;未指定时首条请求使用已有工作区,尚无工作区时使用配置的 `workspacePath` 创建会话。私有 `bindingPath` 文件以原子替换保存当前会话和导航序号。重启后的下一条消息复用该身份;原会话缺失或仍使用旧编程模式时报告错误,不悄悄另建会话;明确开始新实验后采用实验模式,旧对话继续保留。 diff --git a/moss-model.patch.yml b/moss-model.patch.yml index 75e7aa04216..ac3a8dd5e86 100644 --- a/moss-model.patch.yml +++ b/moss-model.patch.yml @@ -12,7 +12,9 @@ config: root: !!js process.env.MOSS_PLUGIN_ROOT data: !!js process.env.MOSS_PLUGIN_DATA + state: !!js process.env.MOSS_PLUGIN_STATE dependencyHome: !!js process.env.LABSCRIPTAI_HOME + visionPython: !!js process.env.MOSS_VISION_PYTHON version: !!js process.env.MOSS_PLUGIN_VERSION timeoutMs: 300000 - id: experiment-preview @@ -67,23 +69,25 @@ description: 实验方案、三维预览和机器人运行 order: 4 plugins: - - id: persona - name: '@deepseek-ai/dsh-persona' + - id: labscriptai-tools + name: './internal/experiment/labscriptai-tools.mjs' config: prefix: >- You are the laboratory experiment assistant. Respond briefly in the user's language. For a simple echo or connectivity test, respond directly. While preparing, accept amendments. Preserve confirmed conditions and the same experiment ID. When essential conditions are missing, call request_experiment_input with one grouped question and wait. - Confirm Flex or OT-2 before choosing the protocol API, labware, pipettes, and slot layout. + Read the selected robot's LabscriptAI authoring context before choosing equipment or slots. For a follow-up, read the current experiment revision, update it, and analyze the new revision. Create a new experiment only on explicit request or when the session has no experiment yet. - Use the experiment tools for local analysis and preview. Physical results require a real run. - When explicitly asked to operate a physical robot, use the robot tools and the workbench confirmation. - Read get_robot_run for actual results. If the connection drops, read the run before attempting any further operation. + Save each draft with the MOSS experiment tools. Analyze its current revision with analyze_experiment for the workbench preview. + In LabscriptAI file_path and protocol_path arguments, current_protocol.py refers to the saved experiment in this conversation. + Follow the LabscriptAI workflow and read_labscriptai_guidance. Use its tools for device status, on-demand photos, local deck vision, additional checks, and recovery. + Only an explicit request for physical operation may trigger the workbench device confirmation. An ambiguous reply is insufficient. + To run the saved, analyzed revision, call mcp__labscriptai__run_protocol with file_path current_protocol.py. The workbench confirmation covers supported minor automatic recovery on that run. + Watch that run with mcp__labscriptai__runtime_watch after start is acknowledged. Read get_robot_run when the watch finishes to confirm the recorded outcome. Use query_history or get_robot_run for read-only status. After a disconnect use safe_next_action and check the original run before acting. + Capture images and run deck vision on request or when LabscriptAI identifies a layout question. Report only checks that ran and observations actually returned. Do not inspect or modify application code or run shell commands. - complete: true - includeRuntimeContext: false - id: robot-tools name: './internal/experiment/robot-tools.mjs' - id: compaction diff --git a/moss-start.mjs b/moss-start.mjs index a0ced1a0190..7136acc54be 100644 --- a/moss-start.mjs +++ b/moss-start.mjs @@ -47,7 +47,7 @@ const child = spawn(process.execPath, [ ? [resolve(root, 'node_modules/@deepseek-ai/dsh/lib/bin.js')] : ['--import', 'tsx/esm', 'apps/cli/src/bin.ts']), '--profile', 'web', '--patch', patchPath, ...process.argv.slice(2), -], { cwd: root, env: { ...process.env, DSH_HOME: dataDir, MOSS_EXPERIMENT_DB: experimentDb, MOSS_PLUGIN_ROOT: runtime.root, MOSS_PLUGIN_DATA: runtime.data, LABSCRIPTAI_HOME: runtime.dependencyHome, MOSS_PLUGIN_VERSION: runtime.version, MOSS_PREVIEW_TMP: previewDir, MOSS_DEMO_TMP: demoDir }, stdio: 'inherit' }) +], { cwd: root, env: { ...process.env, DSH_HOME: dataDir, MOSS_EXPERIMENT_DB: experimentDb, MOSS_PLUGIN_ROOT: runtime.root, MOSS_PLUGIN_DATA: runtime.data, MOSS_PLUGIN_STATE: resolve(dataDir, 'labscriptai'), LABSCRIPTAI_HOME: runtime.dependencyHome, MOSS_PLUGIN_VERSION: runtime.version, MOSS_PREVIEW_TMP: previewDir, MOSS_DEMO_TMP: demoDir }, stdio: 'inherit' }) process.on('exit', cleanup) for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => child.kill(signal)) child.on('error', error => { console.error('网页启动失败:', error.message); process.exitCode = 1 }) diff --git a/packages/interaction/user-approval/README.i18n.yaml b/packages/interaction/user-approval/README.i18n.yaml index d648bb92f30..a8a2100837d 100644 --- a/packages/interaction/user-approval/README.i18n.yaml +++ b/packages/interaction/user-approval/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3618ddc3386e65f0 zh: d6c0ac91aae122bb /deepseek-ai-dsh-user-approval/use-this-package/setting-the-policy: - en: 79f3334a395b9368 - zh: 0c4026b505ee254a + en: 2a6965435128e17f + zh: 7f63ef5dbef4f38a /deepseek-ai-dsh-user-approval/use-this-package/requesting-a-decision: en: dc465de82799bab0 zh: 51144cc77bb15689 diff --git a/packages/interaction/user-approval/README.md b/packages/interaction/user-approval/README.md index 1ac2fce1d8e..dce65650ec6 100644 --- a/packages/interaction/user-approval/README.md +++ b/packages/interaction/user-approval/README.md @@ -33,7 +33,7 @@ Answerers are `approval/request` waterfall listeners: return an outcome to answe ### Setting the policy -The effective policy is the one set for the session, falling back to the configured default. `ask` (the default) delegates to the composed answerers; `never` rejects every request deterministically before interactive dispatch — the strict headless stance for CI and unattended runs. +The effective policy is the one set for the session, falling back to the configured default. `ask` (the default) delegates to the composed answerers. `never` rejects session-policy requests before interactive dispatch. A trusted host may call `request(req, { policy: 'ask' })` for an operation with its own approval rules, such as physical device control. The request uses the same answerers and audit events and leaves the session policy intact. ```yaml - name: '@deepseek-ai/dsh-session-projection' diff --git a/packages/interaction/user-approval/README.zh.md b/packages/interaction/user-approval/README.zh.md index 1dabd4bfe98..3bc35d62f19 100644 --- a/packages/interaction/user-approval/README.zh.md +++ b/packages/interaction/user-approval/README.zh.md @@ -33,7 +33,7 @@ kind: "package-reference" ### 设置策略 -有效策略取会话中已设置的策略,并回退到配置的默认值。`ask`(默认)委托给已组合的应答者;`never` 在交互式分发之前确定性地拒绝每个请求——这是 CI 与无人值守运行采用的严格无头模式。 +有效策略取会话中已设置的策略,并回退到配置的默认值。`ask`(默认)委托给已组合的应答者。`never` 在交互式分发之前拒绝受会话策略约束的请求。设备控制等操作拥有独立审批规则时,可信主机可调用 `request(req, { policy: 'ask' })`。请求仍使用相同的应答者和审计事件,会话策略保持原值。 ```yaml - name: '@deepseek-ai/dsh-session-projection' diff --git a/packages/interaction/user-approval/src/index.ts b/packages/interaction/user-approval/src/index.ts index df48aca514c..835ef297075 100644 --- a/packages/interaction/user-approval/src/index.ts +++ b/packages/interaction/user-approval/src/index.ts @@ -235,11 +235,12 @@ export class ApprovalService extends Service { * authoritative append cannot reject the request or suppress its matching * audit event. * @param req - the pending decision (agent, tool identity, reason, signal). + * @param options - a host-owned interactive policy for an independent operation. * @returns the closed outcome; `'allowed-once'` is the only grant. * @throws when no turn is open or either audit event fails before the session * append commit point. */ - async request(req: ApprovalRequest): Promise { + async request(req: ApprovalRequest, options?: { readonly policy: 'ask' }): Promise { const session = req.agent.session if (!this.approvalStateOf(session).turnOpen) { throw new Error( @@ -255,7 +256,7 @@ export class ApprovalService extends Service { ...req.callId !== undefined ? { callId: req.callId } : {}, ...req.reason !== undefined ? { reason: req.reason } : {}, }) - const outcome = await this.decide(req, session) + const outcome = await this.decide(req, options?.policy ?? this.effectivePolicy(session)) session.append('approval/decided', { id, outcome }) return outcome } @@ -287,10 +288,10 @@ export class ApprovalService extends Service { /** * Dispatch the waterfall, contained and raced against the request signal. * @param req - the borrowed public request. - * @param session - the request agent's session used for policy lookup. + * @param policy - the policy resolved for this operation by the host. * @returns the normalized closed outcome. */ - private async decide(req: ApprovalRequest, session: Session): Promise { + private async decide(req: ApprovalRequest, policy: ApprovalPolicy): Promise { const signal = req.signal if (signal?.aborted) return 'cancelled' // The 'never' policy is decided HERE, before any dispatch: a listener @@ -298,7 +299,7 @@ export class ApprovalService extends Service { // ahead of any gate LISTENER, so a listener-shaped gate cannot keep the // documented promise that 'never' rejects deterministically regardless // of registration order — only the service's own request path can. - if (this.effectivePolicy(session) === 'never') return 'rejected' + if (policy === 'never') return 'rejected' // Enter the promise chain BEFORE dispatching: a listener that throws // SYNCHRONOUSLY (before its first await) must land in the same rejection // path as an async one — `Promise.resolve(call())` would let it escape diff --git a/packages/interaction/user-approval/tests/approval.spec.ts b/packages/interaction/user-approval/tests/approval.spec.ts index 03886992f32..9bb33a01087 100644 --- a/packages/interaction/user-approval/tests/approval.spec.ts +++ b/packages/interaction/user-approval/tests/approval.spec.ts @@ -416,6 +416,17 @@ describe('approval policy (the approval/policy fold)', () => { expect(session.snapshotEvents().filter(e => e.type === 'approval/decided')).toHaveLength(1) }) + it('can ask for an independently governed device action without changing the session policy', async () => { + const ctx = await context() + await ctx.plugin(ApprovalService, { policy: 'never' }) + const { agent } = sessionAgent(ctx, 'sess-device') + const consulted = vi.fn(() => Promise.resolve('allowed-once')) + ctx.on('approval/request', consulted) + await expect(ctx.approval.request({ agent, toolName: 'robot' }, { policy: 'ask' })).resolves.toBe('allowed-once') + await expect(ctx.approval.request({ agent, toolName: 'bash' })).resolves.toBe('rejected') + expect(consulted).toHaveBeenCalledTimes(1) + }) + it('the gate decides FIRST even against an answerer registered before the service (prepend)', async () => { const ctx = await context() ctx.on('approval/request', () => Promise.resolve('allowed-once')) diff --git a/scripts/check-labscriptai.mjs b/scripts/check-labscriptai.mjs index a382a79e89a..d452b25e9a9 100644 --- a/scripts/check-labscriptai.mjs +++ b/scripts/check-labscriptai.mjs @@ -11,6 +11,10 @@ const ctx = new Context() try { await ctx.plugin(LocalSandboxProvider, {}).await() const client = createPluginClient({ ...runtime, timeoutMs: 300000, sandbox: ctx.sandbox }) + const tools = new Set((await client.catalog()).map(tool => tool.name)) + for (const name of ['robot_status', 'capture_image', 'deck_vision_check', 'runtime_watch', 'safe_next_action']) { + assert.ok(tools.has(name), `LabscriptAI did not publish ${name}`) + } const protocol = await readFile(new URL('../internal/experiment/example_transfer.py', import.meta.url), 'utf8') const analysis = await client.analyze(protocol) const documents = await client.documents(analysis) diff --git a/snapshots/session/moss-labscriptai-status/labscriptai-fixture.mjs b/snapshots/session/moss-labscriptai-status/labscriptai-fixture.mjs new file mode 100644 index 00000000000..82125bebbd6 --- /dev/null +++ b/snapshots/session/moss-labscriptai-status/labscriptai-fixture.mjs @@ -0,0 +1,29 @@ +/** Inject a predictable robot status behind the experiment assistant's real MCP tool registration. */ +export const name = 'moss-labscriptai-fixture' +export const inject = ['workingDirectory'] + +/** Provide a scoped test catalog and one read-only call. */ +export function apply(ctx) { + const robot = { origin: 'http://robot.invalid:31950' } + const directory = ctx.workingDirectory + ctx.effect(() => { + const contextText = directory.contextText + directory.contextText = () => 'The current experiment does not use files.' + return () => { directory.contextText = contextText } + }, 'fixture.directory-context') + ctx.effect(() => ctx.provide('experimentStore', { latestForSession: () => null }), 'fixture.experiment') + ctx.effect(() => ctx.provide('robotControl', { target: () => robot }), 'fixture.robot') + ctx.effect(() => ctx.provide('labscriptaiRuntime', { + workflow: async () => 'Read the connected robot before working on the protocol.', + catalog: async () => [{ + name: 'robot_status', description: 'Read the connected robot.', + inputSchema: { type: 'object', properties: { include_modules: { type: 'boolean' } } }, + }], + async experiment(target, name, args, { sessionId }) { + if (target !== robot || name !== 'robot_status' || args.session_id !== sessionId || args.robot_ip !== robot.origin || args.include_modules !== true) { + throw new Error('Unexpected request to the LabscriptAI status fixture.') + } + return { content: [{ type: 'text', text: JSON.stringify({ success: true, data: { modules: [{ slot: 'C1', model: 'temperatureModuleV2' }] } }) }] } + }, + }), 'fixture.labscriptai') +} diff --git a/snapshots/session/moss-labscriptai-status/runtime.cordis.yml b/snapshots/session/moss-labscriptai-status/runtime.cordis.yml new file mode 100644 index 00000000000..3bfc7c85dba --- /dev/null +++ b/snapshots/session/moss-labscriptai-status/runtime.cordis.yml @@ -0,0 +1,11 @@ +- id: tool-bash + disabled: true +- id: tool-pwsh + disabled: true +- insert: + - id: moss-labscriptai-fixture + name: ./labscriptai-fixture.mjs + - id: labscriptai-tools + name: ../../../internal/experiment/labscriptai-tools.mjs + config: + prefix: Read the target robot's status with LabscriptAI. diff --git a/snapshots/session/moss-labscriptai-status/session.v4.jsonl b/snapshots/session/moss-labscriptai-status/session.v4.jsonl new file mode 100644 index 00000000000..a65d3563503 --- /dev/null +++ b/snapshots/session/moss-labscriptai-status/session.v4.jsonl @@ -0,0 +1,22 @@ +{"type":"session","version":4,"id":"{{session:1}}","createdAt":1783352044766,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} +{"type":"sandbox/mode","data":{"mode":"danger-full-access"}} +{"type":"approval/policy","data":{"policy":"never"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Read the LabscriptAI robot status including modules. Which module is in C1?"}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} +{"type":"turn/start","data":{"turn":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Read the LabscriptAI robot status including modules. Which module is in C1?"}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nThe current experiment does not use files."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"The current experiment does not use files."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} +{"type":"session/title","data":{"title":"Read the LabscriptAI robot status","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_labscriptai_status","name":"mcp__labscriptai__robot_status","arguments":"{\"include_modules\":true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":2879,"outputTokens":89,"cacheReadTokens":0,"reasoningTokens":17},"stream":[{"type":"chunk","time":1791427900980,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791427900980,"index":0,"dt":[],"id":"call_labscriptai_status","name":"mcp__labscriptai__robot_status","args":["{\"include_modules\":true}"]},{"type":"chunk","time":1791427900980,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_labscriptai_status","name":"mcp__labscriptai__robot_status","arguments":"{\"include_modules\":true}"}}},{"type":"chunk","time":1791427900980,"chunk":{"type":"usage","usage":{"inputTokens":2879,"outputTokens":89,"cacheReadTokens":0,"reasoningTokens":17}}},{"type":"chunk","time":1791427900980,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_labscriptai_status","name":"mcp__labscriptai__robot_status","arguments":"{\"include_modules\":true}"}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_labscriptai_status"},"toolCallId":"call_labscriptai_status","content":[{"type":"text","text":"{\"success\":true,\"data\":{\"modules\":[{\"slot\":\"C1\",\"model\":\"temperatureModuleV2\"}]}}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":1}} +{"type":"step/start","data":{"turn":1,"step":2}} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"C1 has a temperature module."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":170,"outputTokens":28,"cacheReadTokens":2816,"reasoningTokens":25},"stream":[{"type":"chunk","time":1791427900980,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1791427900980,"index":0,"dt":[],"texts":["C1 has a temperature module."]},{"type":"chunk","time":1791427900980,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"C1 has a temperature module."}}},{"type":"chunk","time":1791427900980,"chunk":{"type":"usage","usage":{"inputTokens":170,"outputTokens":28,"cacheReadTokens":2816,"reasoningTokens":25}}},{"type":"chunk","time":1791427900980,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":2}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/moss-labscriptai-status/snapshot.yml b/snapshots/session/moss-labscriptai-status/snapshot.yml new file mode 100644 index 00000000000..ff77161dff1 --- /dev/null +++ b/snapshots/session/moss-labscriptai-status/snapshot.yml @@ -0,0 +1,8 @@ +version: 1 +scenario: moss-labscriptai-status +profile: headless +composition: default +recording: authored +header: + class: moss-labscriptai-status + pin: true diff --git a/snapshots/session/moss-labscriptai-status/system-prompt.expected.md b/snapshots/session/moss-labscriptai-status/system-prompt.expected.md new file mode 100644 index 00000000000..62a71ad958b --- /dev/null +++ b/snapshots/session/moss-labscriptai-status/system-prompt.expected.md @@ -0,0 +1,3 @@ +Read the target robot's status with LabscriptAI. + +Read the connected robot before working on the protocol. diff --git a/snapshots/session/moss-labscriptai-status/tool-schemas.expected.json b/snapshots/session/moss-labscriptai-status/tool-schemas.expected.json new file mode 100644 index 00000000000..5edb4cedf3e --- /dev/null +++ b/snapshots/session/moss-labscriptai-status/tool-schemas.expected.json @@ -0,0 +1,606 @@ +{ + "initial": [ + { + "name": "create_goal", + "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The concrete completion objective inferred from the direct human request." + }, + "max_goal_rounds": { + "type": "number", + "description": "Optional positive safe-integer limit on automatic continuation rounds." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "edit", + "description": "Edit an existing UTF-8 text file by replacing literal text.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to edit, resolved by the filesystem backend. Provide `file_path` before `old_string` and `new_string` in the arguments." + }, + "old_string": { + "type": "string", + "description": "Literal text to replace." + }, + "new_string": { + "type": "string", + "description": "Literal replacement text. Use an empty string to delete the match." + }, + "replace_all": { + "type": "boolean", + "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "file_path", + "old_string", + "new_string" + ] + } + }, + { + "name": "get_goal", + "description": "Read the current session goal, including the id and revision that update_goal requires.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "glob", + "description": "Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Glob pattern to match file paths against (e.g. \"**/*.ts\", \"src/**/*.test.js\"). A pattern with no \"/\" matches the basename at any depth, so \"*\" and \"*.ts\" both search the whole tree; include a separator to anchor the depth." + }, + "path": { + "type": "string", + "description": "Directory to search in. Defaults to the session workspace; a relative path resolves against it." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "grep", + "description": "Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. Returns up to 250 matches; a larger result reports where the complete match list was saved.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Regular expression to search for (ripgrep syntax)." + }, + "path": { + "type": "string", + "description": "File or directory to search. Defaults to the session workspace; a relative path resolves against it." + }, + "include": { + "type": "string", + "description": "One glob filter for which files to search (e.g. \"*.ts\", \"*.{js,jsx}\"). Not a list; negation is not supported." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "interrupt_agent", + "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local direct child's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", + "parameters": { + "type": "object", + "properties": { + "agent_id": { + "type": "string", + "description": "The id of an agent created under you: your direct child or a deeper descendant." + } + }, + "required": [ + "agent_id" + ] + } + }, + { + "name": "job_kill", + "description": "Request cancellation of a running background job.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "reason": { + "type": "string", + "description": "Optional short reason, recorded in the log and forwarded to the job." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "job_list", + "description": "List your background jobs (running and finished) with their ids, kinds, and statuses.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "job_output", + "description": "Read a background job: output since the previous read for stream jobs, or the result of a finished final-output job.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "wait": { + "type": "boolean", + "description": "Block until the job finishes or the timeout expires; a timed-out wait leaves the job running. Defaults to false." + }, + "timeout_ms": { + "type": "number", + "description": "Max wait in milliseconds with wait: true. Defaults to and is capped by configuration." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "list_agents", + "description": "List subagents you started, with their ids, labels, and status. running means it is working; inactive means it is not currently working. You will be notified when a subagent finishes; there is no need to keep checking its status. Use send_message to continue the conversation.", + "parameters": { + "type": "object", + "properties": { + "scope": { + "type": "string", + "description": "children (default) lists direct children, which accept send_message in any status. descendants lists the whole tree below you with each entry's parent session id and depth; entries deeper than 1 accept only interrupt_agent.", + "enum": [ + "children", + "descendants" + ] + } + } + } + }, + { + "name": "mcp__labscriptai__robot_status", + "description": "Read the connected robot.", + "parameters": { + "type": "object", + "properties": { + "include_modules": { + "type": "boolean" + } + } + } + }, + { + "name": "read", + "description": "Read a UTF-8 text file and return line-numbered content.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to read, resolved by the filesystem backend." + }, + "offset": { + "type": "number", + "description": "1-based first line to return. Defaults to 1." + }, + "limit": { + "type": "number", + "description": "Maximum number of lines to return. Defaults to 2000." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "read_image", + "description": "Read a PNG/JPEG/WebP/GIF file and return the image itself. Large images are downscaled automatically; do not install image libraries or create thumbnails to inspect an image.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to the image file, resolved by the filesystem backend." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "read_labscriptai_guidance", + "description": "Read the pinned LabscriptAI workflow, recovery rules, or operating policy when the experiment needs that detail.", + "parameters": { + "type": "object", + "properties": { + "topic": { + "type": "string", + "enum": [ + "workflows", + "error-response", + "safety-policy" + ] + } + }, + "required": [ + "topic" + ] + } + }, + { + "name": "send_message", + "description": "Send a message to an agent. A working agent receives it at its next step; an idle agent starts a new turn with it. Returns delivery confirmation, not the agent's answer.", + "parameters": { + "type": "object", + "properties": { + "agent_id": { + "type": "string", + "description": "The agent id of your direct continuable child, or your direct parent when you are a resident continuable child." + }, + "message": { + "type": "string", + "description": "The message to deliver to the agent." + } + }, + "required": [ + "agent_id", + "message" + ] + } + }, + { + "name": "skill", + "description": "Load the full instructions for a skill. Call it before acting on a task that names or clearly matches a skill in the session skill catalog.", + "parameters": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The exact skill name from the available skills list." + } + }, + "required": [ + "name" + ] + } + }, + { + "name": "subagent", + "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its id. The runtime notifies you when it finishes. The child reports results with `send_message`; use `send_message` to steer it while running or continue its conversation after it finishes.", + "parameters": { + "type": "object", + "properties": { + "cwd": { + "type": "string", + "description": "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent." + }, + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "subagent_fork", + "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its id. The runtime notifies you when it finishes. The child reports results with `send_message`; use `send_message` to steer it while running or continue its conversation after it finishes.", + "parameters": { + "type": "object", + "properties": { + "cwd": { + "type": "string", + "description": "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent." + }, + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "todo_write", + "description": "Record and update a task list to plan multi-step work and show progress; skip it for trivial single-step tasks. Add one todo per concrete step before you start. While work remains, keep the todos being worked on `in_progress`, several only when work runs in parallel. Mark each todo `completed` as soon as it is done.", + "parameters": { + "type": "object", + "properties": { + "todos": { + "type": "array", + "description": "The COMPLETE task list, replacing any previous list.", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "content": { + "type": "string", + "description": "What the task is — a short imperative line." + }, + "status": { + "type": "string", + "description": "pending (not started) | in_progress (now) | completed (done).", + "enum": [ + "pending", + "in_progress", + "completed" + ] + } + }, + "required": [ + "content", + "status" + ] + } + } + }, + "required": [ + "todos" + ] + } + }, + { + "name": "update_goal", + "description": "Update the current goal.", + "parameters": { + "type": "object", + "properties": { + "goal_id": { + "type": "string", + "description": "Exact id returned by get_goal." + }, + "revision": { + "type": "number", + "description": "Exact positive revision returned by get_goal." + }, + "action": { + "type": "string", + "description": "edit, pause, and resume require a direct top-level human request. complete and blocked are also allowed during an automatic continuation of this goal; blocked is rejected before the configured minimum round count.", + "enum": [ + "edit", + "pause", + "resume", + "complete", + "blocked" + ] + }, + "objective": { + "type": "string", + "description": "Replacement objective; valid only with action edit." + }, + "max_goal_rounds": { + "type": "number", + "description": "Replacement cap; valid only with action edit." + }, + "blocked_reason": { + "type": "string", + "description": "Required only with action blocked: the concrete condition that persisted across rounds and blocks progress." + } + }, + "required": [ + "goal_id", + "revision", + "action" + ] + } + }, + { + "name": "web_fetch", + "description": "Fetch the content of a specific HTTP(S) URL and return it decoded to text.", + "parameters": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The HTTP(S) URL to fetch." + } + }, + "required": [ + "url" + ] + } + }, + { + "name": "web_search", + "description": "Search the web for current information. Returns an optional summary answer and a list of source URLs.", + "parameters": { + "type": "object", + "properties": { + "queries": { + "type": "array", + "description": "1–4 search queries; their results are merged.", + "items": { + "type": "string" + } + } + }, + "required": [ + "queries" + ] + } + }, + { + "name": "workflow", + "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides.\n- `pipeline(items, ...stages): Promise` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. A stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) end the whole script instead of producing `null`. The script has no filesystem, network, timer, or Node.js APIs; the agents do the work.", + "parameters": { + "type": "object", + "properties": { + "script": { + "type": "string", + "description": "The plain JavaScript body, not TypeScript and without an `export const meta` statement; top-level await is allowed. End with `return `; the JSON-serializable value is this tool's result." + }, + "meta": { + "type": "object", + "description": "The workflow identity as plain JSON, not code.", + "additionalProperties": true, + "properties": { + "name": { + "type": "string", + "description": "Short kebab-case workflow name." + }, + "description": { + "type": "string", + "description": "One-line description of what the workflow does." + }, + "whenToUse": { + "type": "string", + "description": "Optional guidance on when this workflow applies." + }, + "phases": { + "type": "array", + "description": "Optional phase declarations matched by phase() calls.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "title": { + "type": "string", + "description": "The phase title phase() calls match by exact string." + }, + "detail": { + "type": "string", + "description": "Optional one-line description of the phase." + }, + "provider": { + "type": "string", + "description": "Optional provider override this phase is expected to use." + }, + "model": { + "type": "string", + "description": "Optional model override this phase is expected to use." + } + }, + "required": [ + "title" + ] + } + } + }, + "required": [ + "name", + "description" + ] + }, + "args": { + "type": "object", + "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", + "additionalProperties": true + }, + "run_in_background": { + "type": "boolean", + "description": "Run as a background job: return a job id immediately instead of waiting; the return value arrives with the completion notice." + } + }, + "required": [ + "script", + "meta" + ] + } + }, + { + "name": "working_directory", + "description": "Read the current working directory, or change it with cd. Relative paths use the current directory. Existing shells and running processes keep their own directories.", + "parameters": { + "type": "object", + "properties": { + "cd": { + "type": "string", + "description": "Existing directory to enter. Omit to read the current directory." + } + } + } + }, + { + "name": "write", + "description": "Create or fully replace a UTF-8 text file.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to write, resolved by the filesystem backend. Provide `file_path` before `content` in the arguments." + }, + "content": { + "type": "string", + "description": "Full UTF-8 text content to write." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "file_path", + "content" + ] + } + } + ], + "changes": [] +} From efcc1e3b086ae9c8d74de2dc2add1a263841db10 Mon Sep 17 00:00:00 2001 From: Ian <96117378+zhangyuian@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:53:01 +0800 Subject: [PATCH 2/5] Keep Xiaozhi voice replies short and stop replaying old answers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The voice bridge now speaks only the conclusion (first sentence, at most 40 characters), greets with 收到。 and a single 还在做。, and ends the turn after a wait or question so the device can listen again. request_experiment_input accepts a voice_question that names only the missing facts, and a new request no longer replays the previous finished answer; an explicit progress query still reports it. Restore the voice diagnostics log for device-side verification. --- internal/experiment/agent-tools.mjs | 13 ++- internal/xiaozhi/README.i18n.yaml | 4 +- internal/xiaozhi/README.md | 2 +- internal/xiaozhi/README.zh.md | 2 +- internal/xiaozhi/bridge.mjs | 21 ++++- internal/xiaozhi/bridge.test.mjs | 14 ++- internal/xiaozhi/delegation.mjs | 5 +- internal/xiaozhi/plugin.mjs | 14 +-- internal/xiaozhi/voice-feedback.mjs | 119 ++++++++++++++++++++++--- internal/xiaozhi/voice-policy.test.mjs | 81 ++++++++++++++++- moss-model.patch.yml | 4 + 11 files changed, 240 insertions(+), 39 deletions(-) diff --git a/internal/experiment/agent-tools.mjs b/internal/experiment/agent-tools.mjs index 01beff4c815..9fb731973c9 100644 --- a/internal/experiment/agent-tools.mjs +++ b/internal/experiment/agent-tools.mjs @@ -36,15 +36,20 @@ export function apply(ctx) { }), 'experiment-agent-tools.guidance') ctx.tools.register(defineTool({ name: 'request_experiment_input', - description: 'Ask one concise question for essential experiment details, then wait for the operator to answer.', - parameters: { question: { type: 'string', required: true, description: 'Question in the operator’s language.' } }, + description: 'Ask one concise question for essential experiment details, then wait for the operator to answer. When the message came from 小智, also pass voice_question: one short spoken line naming only the missing facts, at most 30 characters, for example 还需要:目标板孔位、每孔体积。', + parameters: { + question: { type: 'string', required: true, description: 'Question in the operator’s language.' }, + voice_question: { type: 'string', description: 'Optional spoken one-liner for the voice device: only the missing facts, at most 30 characters.' }, + }, output, async execute(args, exec) { if (!args.question.trim() || Buffer.byteLength(args.question) > 2000) throw new Error('A concise nonempty question is required.') + const voice = typeof args.voice_question === 'string' ? args.voice_question.trim() : '' + if (voice && [...voice].length > 40) throw new Error('voice_question must be at most 40 characters.') const intent = ctx.get('mossVoiceIntent')?.captureIntent(sessionId(exec)) intent?.assertCurrent() - intent?.needsInput(args.question) - return { status: 'needs_input', question: args.question } + intent?.needsInput(args.question, voice || undefined) + return { status: 'needs_input', question: args.question, ...(voice ? { voice_question: voice } : {}) } }, })) diff --git a/internal/xiaozhi/README.i18n.yaml b/internal/xiaozhi/README.i18n.yaml index 0c5af7f2dfe..b27b85a0e10 100644 --- a/internal/xiaozhi/README.i18n.yaml +++ b/internal/xiaozhi/README.i18n.yaml @@ -3,5 +3,5 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write internal/xiaozhi/README.md /xiaozhi-mcp-bridge: - en: 8111d1a42982b072 - zh: 970760fa5a51f5fa + en: a052017f0cbc5c03 + zh: 3ca9851a474d2e44 diff --git a/internal/xiaozhi/README.md b/internal/xiaozhi/README.md index 600b6bb5f00..979a840f4fc 100644 --- a/internal/xiaozhi/README.md +++ b/internal/xiaozhi/README.md @@ -18,7 +18,7 @@ This is a single-operator deployment. The Xiaozhi endpoint does not provide a ve While an experiment question is open, **Continue on web** opens a reply form for that question. The form remains available while Xiaozhi reconnects. The authenticated POST accepts `replyTo` with the displayed job ID and returns 409 if a newer request already replaced it. -Speech decisions limit automatic waiting acknowledgements to three per task cycle at offsets 0, 15 and 45 seconds. The voice bridge wakes a pending status query when `request_experiment_input` publishes a question. `awaitingConfirmation=true` directs the voice caller to speak the question once and wait for an answer. A clarification longer than 80 characters is condensed to its leading clause plus `详细问题请看电脑`, and the same short text is returned as the spoken question, so the device does not read lists or tables; the full question stays in the workbench. An explicit progress query can repeat it without spending the waiting budget. While awaiting an answer, short voice replies such as `50 microliters` or `OT-2` stay in the current session even if marked `newExperiment=true`. The bridge also accepts `newTask` as an alias. After an answer, polling the previous receipt returns `followJobId` and stays silent. Completion uses one short sentence during an active voice dialog. The hosted model controls actual speech, which requires device testing. +Speech decisions keep the voice channel short. The delegate receipt speaks `收到。` and asks the caller to keep polling `moss_task_status`; the later waiting acknowledgement is `还在做。` and ends the reply so the device returns to listening, because an open reply keeps the device in its speaking state and the operator cannot interrupt it. Each decision carries `next`: `poll` keeps observing, `end-turn` reads the sentence and ends the reply, and `wait` stays quiet while observation continues. A clarification speaks the workbench `voice_question` when the assistant supplied one (`request_experiment_input` accepts a one-line `voice_question` of at most 40 characters naming only the missing facts); otherwise a long question is condensed to its leading clause plus `详细问题请看电脑`, and the full question stays in the workbench. Completion speaks the first sentence of the answer, clipped to 40 characters and followed by `详情看电脑。` when the report is longer. A new request never replays the previous answer; an explicit progress query still reports a result that finished while the device was disconnected. While awaiting an answer, short voice replies such as `50 microliters` or `OT-2` stay in the current session even if marked `newExperiment=true`. The bridge also accepts `newTask` as an alias. After an answer, polling the previous receipt returns `followJobId` and stays silent. The MCP endpoint is request/response and offers no idle-device push channel. The hosted model controls actual speech, which requires device testing; `diagnosticsPath` records connection changes, tool names and speech decisions. Run focused checks from the project root with Node 24.9 or later: diff --git a/internal/xiaozhi/README.zh.md b/internal/xiaozhi/README.zh.md index 81084d70531..65e65f8cd9a 100644 --- a/internal/xiaozhi/README.zh.md +++ b/internal/xiaozhi/README.zh.md @@ -18,7 +18,7 @@ 实验正在等你回答时,点击 **在网页继续** 即可输入回答。小智重连期间也能使用。经过认证的 POST 使用 `replyTo` 指定当前问题对应的任务;如果已有更新的请求替代这个问题,会返回 409。 -自动等待播报每个任务周期最多三次,默认在第 0、15、45 秒。`request_experiment_input` 发布问题时,语音桥立即唤醒正在等待的状态查询。`awaitingConfirmation=true` 提示小智播报问题一次,然后等用户回答。超过 80 字的追问会压缩成开头一句加“详细问题请看电脑”,返回的播报问题和结果都用这句短话,设备不会朗读清单或表格;完整问题保留在工作台。用户主动问进度时可以再播一次,不占等待提示次数。等待回答期间,像「50 微升」或「OT-2」这样的简短语音回答,即使被误标为 `newExperiment=true` 也会留在当前会话。语音桥也接受 `newTask` 别名。收到回答后,查询上一条回执会返回 `followJobId` 并保持静默。完成时在活跃语音对话中只播报一句短话。实际播报由托管模型决定,仍需在设备上验证。 +语音播报保持简短。交办回执只说“收到。”,并要求调用方继续调用 `moss_task_status`;之后的等待提示是“还在做。”,说完就结束本轮,让设备回到聆听状态,因为回复不结束,设备就一直停在说话状态,无法打断。每条播报决定带 `next`:`poll` 表示继续观察,`end-turn` 表示朗读后结束本轮,`wait` 表示保持安静并继续观察。追问优先播报工作台填写的 `voice_question`(`request_experiment_input` 可带一行最关键的缺失信息,最多 40 字);没有提供时,长问题压缩成开头一句加“详细问题请看电脑”,完整问题保留在工作台。完成时播报答复的第一句,最长 40 字,内容更长时补一句“详情看电脑。”。新要求不会重播上一条答复;只有用户明确问进度时,才会播报断线期间完成的结果。等待回答期间,像「50 微升」或「OT-2」这样的简短语音回答,即使被误标为 `newExperiment=true` 也会留在当前会话。语音桥也接受 `newTask` 别名。收到回答后,查询上一条回执会返回 `followJobId` 并保持静默。MCP 接入点是请求/响应式的,不提供空闲设备主动推送通道。实际播报由托管模型决定,仍需在设备上验证;`diagnosticsPath` 记录连接变化、工具名称和播报决定。 在项目根目录使用 Node 24.9 或更高版本运行针对性测试: diff --git a/internal/xiaozhi/bridge.mjs b/internal/xiaozhi/bridge.mjs index 7c2688cfcd9..c8af1b91332 100644 --- a/internal/xiaozhi/bridge.mjs +++ b/internal/xiaozhi/bridge.mjs @@ -18,12 +18,12 @@ const tools = [ }, { name: 'moss_delegate', - description: '把用户原话交给电脑上的当前实验助手。生成中改口也立即提交,最新要求覆盖旧要求。用户回答实验问题时继续同一实验,仅明确另开实验才设 newExperiment=true。返回里的 result 和 question 是给电脑端看的简短提示;只按 speech.speak/text 播报一次,不要复述 result、question、JSON 或工具名。awaitingConfirmation=true 时等待用户回答,再调用本工具;否则继续查询最新任务。', + description: '把用户原话交给电脑上的当前实验助手。生成中改口也立即提交,最新要求覆盖旧要求。仅明确另开实验才设 newExperiment=true(也接受 newTask 别名)。严格按返回的 speech.speak/text 播报一次,然后按 speech.next 行动:poll 时继续调用 moss_task_status 观察;end-turn 时朗读后立即结束本轮回复、不再调用任何工具,让设备回到聆听状态;wait 时保持安静继续观察。最多 3 次等待提示。用户提出新要求时先处理这个新要求,不要先回答之前的问题;旧任务的完成结果只在用户明确问进度时朗读。返回里的 result 和 question 是给电脑端看的提示,不要朗读。awaitingConfirmation=true 时朗读问题后结束本轮,等用户回答后再调用本工具。', inputSchema: { type: 'object', properties: { newExperiment: { type: 'boolean', description: '仅当用户明确要求另开新实验时为 true,普通补充和修改保持 false。' }, newTask: { type: 'boolean', description: '兼容旧调用方的别名。新调用使用 newExperiment。' }, message: { type: 'string', minLength: 1, maxLength: 8000, description: '用户提出的完整任务和已知实验条件。' } }, required: ['message'], additionalProperties: false }, }, { name: 'moss_task_status', - description: '持续观察 MOSS 任务。只在 speech.speak=true 时朗读 speech.text 一次,否则保持安静;不要朗读 result、question 或任何长列表,也不要复述电脑上的完整内容,一两次短句即可。遇 followJobId 改查最新任务。awaitingConfirmation=true 时停止自动查询并等待用户回答,再调用 moss_delegate。completed/error 后停止自动查询。仅用户主动问进度时设 userQuery=true。', + description: '持续观察 MOSS 任务。只在 speech.speak=true 时朗读 speech.text 一次;先看 speech.next:poll 时继续调用本工具,end-turn 时朗读后立即结束本轮回复让设备聆听,wait 时保持安静继续查询,不要因为暂时没有播报就停止。遇 followJobId 改查最新任务;用户改口立即改调 moss_delegate。completed/error 后只说指定短句,不读 result、question、JSON 或复述方案。仅用户主动问进度时设 userQuery=true。', inputSchema: { type: 'object', properties: { jobId: { type: 'string', minLength: 1, maxLength: 128 }, userQuery: { type: 'boolean', description: '只有用户明确询问当前进度才为true,自动观察必须false。' } }, required: ['jobId'], additionalProperties: false }, }, ] @@ -86,7 +86,13 @@ export async function handleMessage(message, store, sessionId, delegation, conte try { if (submitting) { const accepted = await delegation.submit(args.message, { newExperiment: args.newExperiment ?? args.newTask ?? false, source: 'xiaozhi' }) - return response(id, text(delegation.voiceReceipt ? { ...accepted, ...delegation.voiceReceipt(accepted.jobId) } : accepted)) + const receipt = delegation.voiceReceipt ? { ...accepted, ...delegation.voiceReceipt(accepted.jobId) } : accepted + let settled = null + if (typeof delegation.voiceSettle === 'function') { + settled = await delegation.voiceSettle(accepted.jobId, { signal: context.signal }) + } + const finished = settled !== null && !['running', 'timeout'].includes(settled.status) + return response(id, text(finished ? { ...receipt, ...settled } : receipt)) } return response(id, text(delegation.voiceStatus ? await delegation.voiceStatus(args.jobId, { userQuery: args.userQuery ?? false, signal: context.signal }) : delegation.get(args.jobId))) } catch (error) { @@ -122,7 +128,7 @@ export function connectBridge({ url, sessionId, store, delegation, liveControl = let socket, retryTimer, heartbeatTimer let attempts = 0 let disposed = false - let state = { status: 'connecting', reconnects: 0, registered: false, lastCall: null, updatedAt: Date.now() } + let state = { status: 'connecting', reconnects: 0, registered: false, lastCall: null, clientInfo: null, updatedAt: Date.now() } const pending = new Set() const snapshot = () => ({ ...state, lastCall: state.lastCall === null ? null : { ...state.lastCall } }) const notify = (status, extra = {}) => { @@ -167,6 +173,12 @@ export function connectBridge({ url, sessionId, store, delegation, liveControl = if (message && message.method === undefined && (Object.hasOwn(message, 'result') || Object.hasOwn(message, 'error'))) return if (message?.id !== undefined && requests.has(JSON.stringify(message.id))) return if (message?.id !== undefined) requests.set(JSON.stringify(message.id), controller) + if (message?.method === 'initialize') notify(state.status, { clientInfo: { + name: typeof message.params?.clientInfo?.name === 'string' ? message.params.clientInfo.name : null, + version: typeof message.params?.clientInfo?.version === 'string' ? message.params.clientInfo.version : null, + protocolVersion: typeof message.params?.protocolVersion === 'string' ? message.params.protocolVersion : null, + capabilities: message.params?.capabilities && typeof message.params.capabilities === 'object' ? Object.keys(message.params.capabilities) : [], + } }) if (message !== undefined) { const name = message.method === 'tools/call' && tools.some(tool => tool.name === message.params?.name) ? message.params.name : null const receivedAt = Date.now() @@ -216,3 +228,4 @@ export function connectBridge({ url, sessionId, store, delegation, liveControl = dispose.snapshot = snapshot return dispose } + diff --git a/internal/xiaozhi/bridge.test.mjs b/internal/xiaozhi/bridge.test.mjs index f63971469ac..347d4b14b4e 100644 --- a/internal/xiaozhi/bridge.test.mjs +++ b/internal/xiaozhi/bridge.test.mjs @@ -32,6 +32,17 @@ test('tool calls are restricted to an operator-selected session and omit snapsho } finally { store.close(); rmSync(dir, { recursive: true, force: true }) } }) +test('the voice tool contract releases the device to listen after an end-turn decision', async () => { + const store = { getForSession() {}, getChecksForSession() {} } + const listing = await handleMessage(request(1, 'tools/list'), store, 'owner') + const byName = new Map(listing.result.tools.map(tool => [tool.name, tool.description])) + assert.match(byName.get('moss_delegate'), /speech\.next/) + assert.match(byName.get('moss_delegate'), /end-turn/) + assert.match(byName.get('moss_delegate'), /最多 3 次等待提示/) + assert.match(byName.get('moss_task_status'), /end-turn/) + assert.match(byName.get('moss_task_status'), /让设备聆听/) +}) + test('reports live-control modes without exposing the robot address', async () => { const store = { getForSession() {}, getChecksForSession() {} } const delegation = { submit() {} } @@ -64,9 +75,10 @@ test('outbound socket sends only replies and is closed on disposal', async () => const dispose = connectBridge({ url: 'wss://example.invalid/path?token=private', sessionId: 'owner', store, WebSocketClass: FakeSocket }) const socket = FakeSocket.last assert.equal(socket.sent.length, 0) - socket.deliver(JSON.stringify(request(1, 'initialize', { protocolVersion: '2024-11-05' }))) + socket.deliver(JSON.stringify(request(1, 'initialize', { protocolVersion: '2024-11-05', clientInfo: { name: 'xz-mcp-broker', version: '0.0.1' }, capabilities: { sampling: {} } }))) await new Promise(resolve => setImmediate(resolve)) assert.equal(socket.sent[0].result.protocolVersion, '2024-11-05') + assert.deepEqual(dispose.snapshot().clientInfo, { name: 'xz-mcp-broker', version: '0.0.1', protocolVersion: '2024-11-05', capabilities: ['sampling'] }) socket.deliver('{') await new Promise(resolve => setImmediate(resolve)) assert.equal(socket.sent[1].error.code, -32700) diff --git a/internal/xiaozhi/delegation.mjs b/internal/xiaozhi/delegation.mjs index 3984fe4f5ce..97438501f78 100644 --- a/internal/xiaozhi/delegation.mjs +++ b/internal/xiaozhi/delegation.mjs @@ -37,7 +37,7 @@ export function createDelegation({ controller, workspaces, events, timeoutMs = 3 } const changed = () => { for (const listener of subscribers) { try { listener() } catch { console.warn('xiaozhi task observer failed') } } } const focus = reason => { focusSequence = Math.max(focusSequence + 1, Date.now()); focusReason = reason } - const publicJob = job => ({ jobId: job.jobId, sessionId: job.sessionId, status: job.status, result: job.result, cycleId: job.cycleId, phase: job.phase, question: job.question, preview: job.preview, supersededBy: job.supersededBy, ...(job.followJobId ? { followJobId: job.followJobId } : {}) }) + const publicJob = job => ({ jobId: job.jobId, sessionId: job.sessionId, status: job.status, result: job.result, cycleId: job.cycleId, phase: job.phase, question: job.question, voiceQuestion: job.voiceQuestion ?? null, preview: job.preview, supersededBy: job.supersededBy, ...(job.followJobId ? { followJobId: job.followJobId } : {}) }) async function admit(message, { newExperiment, source, replyTo }) { if (closed) throw new Error('委派服务已关闭') @@ -164,10 +164,11 @@ export function createDelegation({ controller, workspaces, events, timeoutMs = 3 } return { assertCurrent, - needsInput: question => publish('needs_input', { question }), + needsInput: (question, voiceQuestion) => publish('needs_input', { question, ...(typeof voiceQuestion === 'string' && voiceQuestion.trim() ? { voiceQuestion: voiceQuestion.trim() } : {}) }), previewReady: ({ id, revision }) => publish('preview_ready', { preview: { id, revision } }), } }, close() { closed = true; for (const job of jobs.values()) if (active(job)) job.cancelObservation?.(); subscribers.clear() }, } } + diff --git a/internal/xiaozhi/plugin.mjs b/internal/xiaozhi/plugin.mjs index 9d054c1588f..c921c8cc2fe 100644 --- a/internal/xiaozhi/plugin.mjs +++ b/internal/xiaozhi/plugin.mjs @@ -42,18 +42,18 @@ export function apply(ctx, config) { } }) const feedback = createVoiceFeedback({ delegation, ...config.feedback }) ctx.provide('mossVoiceIntent', delegation) - let seenFocus = 0 - const reportWake = state => { if (state.status === 'error') console.warn('xiaozhi workbench window:', state.reason) } - const stopChanges = delegation.subscribe(() => { - const current = delegation.workbench() - if (current.focusSequence > seenFocus) { seenFocus = current.focusSequence; void wakeup.wake().then(reportWake) } - }) let disconnect, unregister const record = value => { if (!config.diagnosticsPath) return try { appendFileSync(config.diagnosticsPath, JSON.stringify(value) + '\n', { mode: 0o600 }) } catch { console.warn('xiaozhi diagnostics could not be saved') } } + let seenFocus = 0 + const reportWake = state => { if (state.status === 'error') console.warn('xiaozhi workbench window:', state.reason) } + const stopChanges = delegation.subscribe(() => { + const current = delegation.workbench() + if (current.focusSequence > seenFocus) { seenFocus = current.focusSequence; void wakeup.wake().then(reportWake) } + }) const recordSpeech = result => { record({ kind: 'speech_decision', jobId: result.jobId, cycleId: result.cycleId, phase: result.phase, speak: result.speech.speak, reason: result.speech.reason, waitingCount: result.speech.waitingCount, at: Date.now() }); return result } const workbench = { ...delegation, @@ -64,6 +64,7 @@ export function apply(ctx, config) { }, voiceReceipt: id => recordSpeech(feedback.receipt(id)), voiceStatus: async (id, options) => recordSpeech(await feedback.status(id, options)), + voiceSettle: async (id, options) => recordSpeech(await feedback.settle(id, options)), workbench() { return { ...delegation.workbench(), connection: disconnect?.snapshot() ?? { status: 'not_configured', registered: false, reconnects: 0, lastCall: null }, wakeup: wakeup.state(), speechPolicy: feedback.snapshot() } }, @@ -88,3 +89,4 @@ export function apply(ctx, config) { return async () => { stopChanges(); feedback.close(); delegation.close(); const stoppedWake = wakeup.close(); await unregister?.(); await disconnect?.(); await stoppedWake } }, 'xiaozhi-readonly.connection') } + diff --git a/internal/xiaozhi/voice-feedback.mjs b/internal/xiaozhi/voice-feedback.mjs index 53dc370712c..3acbc6708ac 100644 --- a/internal/xiaozhi/voice-feedback.mjs +++ b/internal/xiaozhi/voice-feedback.mjs @@ -1,6 +1,37 @@ /** Bound automatic speech across one task and its amendments; result queries stay cancellable. */ -export function createVoiceFeedback({ delegation, offsetsMs, pollWaitMs, now = Date.now }) { + +/** + * Render one assistant reply as a single short spoken sentence. Markdown tables, + * code fences, links and headings are dropped, then the first sentence is kept + * and clipped to the spoken limit so a voice turn never reads a report aloud. + * @param {unknown} value Assistant reply text. + * @param {{ limit?: number }} [options] Maximum spoken length before clipping. + * @returns {string} Spoken summary, or an empty string when nothing speakable remains. + */ +export function spokenReply(value, { limit = 40 } = {}) { + const text = String(value ?? '') + .replace(/\r\n?/g, '\n') + .replace(/```[\s\S]*?```/g, ' ') + .replace(/^\s*\|.*$/gm, ' ') + .replace(/^\s*[-*+]\s+/gm, '') + .replace(/!\[[^\]]*\]\([^)]*\)/g, ' ') + .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') + .replace(/https?:\/\/\S+/g, ' ') + .replace(/[#>`*_~]+/g, '') + .replace(/\s+/g, ' ') + .trim() + if (!text) return '' + const sentence = (text.match(/^[^。!?!?]*[。!?!?]/)?.[0] ?? text).trim() + const head = sentence.replace(/[,、,;;::]$/, '') + const clipped = head.length <= limit ? head : `${head.slice(0, limit).replace(/[,、,;;::]$/, '')}。` + const more = clipped.length < text.length + if (!more) return clipped + return `${clipped.replace(/[。!?!?]$/, '')}。详情看电脑。` +} + +export function createVoiceFeedback({ delegation, offsetsMs, pollWaitMs, settleMs = 0, now = Date.now }) { if (!Array.isArray(offsetsMs) || offsetsMs.length !== 3 || offsetsMs[0] !== 0 || offsetsMs.some((value, index) => !Number.isSafeInteger(value) || value < 0 || index > 0 && value <= offsetsMs[index - 1]) || !Number.isSafeInteger(pollWaitMs) || pollWaitMs < 1) throw new Error('voice feedback requires three increasing offsets beginning at zero and a positive pollWaitMs') + if (!Number.isSafeInteger(settleMs) || settleMs < 0) throw new Error('voice feedback requires a non-negative settleMs') const cycles = new Map() const lifetime = new AbortController() /** @@ -16,9 +47,28 @@ export function createVoiceFeedback({ delegation, offsetsMs, pollWaitMs, now = D const head = (colon > 0 && colon <= 80 ? flat.slice(0, colon) : flat.slice(0, 80)).replace(/[,、,::;;]$/, '') return `${head}。详细问题请看电脑。` } - const speech = (cycle, speak, text, reason) => ({ speak, text, reason, waitingCount: cycle.count, waitingLimit: 3, instruction: reason === 'needs_input' - ? (speak ? '只朗读 text 一次,然后等用户回答;不要朗读 result 或 question 里的详细内容。' : '保持安静,等用户回答。') - : (speak ? '只朗读 text 一次,不复述任务状态、JSON、工具名或额外解释。' : '保持安静,不播报等待、处理中或任何同义句。继续观察当前任务;用户改口应立即调用 moss_delegate,不能要求等本轮结束。') }) + /** + * One spoken decision. `next` tells the voice caller how the reply must end: + * `poll` keeps observing, `end-turn` releases the device to listen again, and + * `wait` stays quiet while observation continues. + * @param {object} cycle Speech budget for this task cycle. + * @param {boolean} speak Whether the caller should read `text` aloud. + * @param {string} text Sentence to read. + * @param {string} reason Why this decision was made. + * @param {'poll'|'end-turn'|'wait'} next Required turn continuation. + * @returns {object} Public speech decision. + */ + const speech = (cycle, speak, text, reason, next = 'wait') => ({ + speak, text, reason, next, + waitingCount: cycle.count, waitingLimit: 3, + instruction: reason === 'needs_input' + ? (speak ? '只朗读 text 一次,不加任何口头语、不复述用户原话;然后开始等用户回答;不要朗读 result 或 question 里的详细内容。' : '保持安静,等用户回答。') + : next === 'poll' + ? '只朗读 text 一次,不加任何口头语、不复述用户原话;然后继续调用 moss_task_status 观察该任务,不要结束本轮。' + : next === 'end-turn' + ? '只朗读 text 一次,不加任何口头语、不复述用户原话;然后立即结束本轮回复,不要再调用任何工具,让设备回到聆听状态。' + : '保持安静,不播报等待、处理中或任何同义句。继续调用 moss_task_status 观察当前任务,不要结束本轮;用户改口应立即调用 moss_delegate。', + }) const state = id => delegation.get(id) const cycleFor = job => { if (!cycles.has(job.cycleId)) { @@ -35,35 +85,74 @@ export function createVoiceFeedback({ delegation, offsetsMs, pollWaitMs, now = D if (job.status === 'superseded' || job.followJobId) return { ...job, result: null, question: null, awaitingConfirmation: false, speech: speech(cycle, false, '', job.followJobId ? 'continued' : 'superseded'), followJobId: job.followJobId ?? job.supersededBy } if (pendingQuestion(job)) { const speak = userQuery || !questionReported(job, cycle) - const short = spoken(job.question) + const short = typeof job.voiceQuestion === 'string' && job.voiceQuestion ? job.voiceQuestion : spoken(job.question) cycle.question = { jobId: job.jobId, text: job.question } - return { ...job, result: short, question: short, awaitingConfirmation: true, detailsAvailableInWorkbench: true, speech: speech(cycle, speak, speak ? short : '', 'needs_input') } + return { ...job, result: short, question: short, awaitingConfirmation: true, detailsAvailableInWorkbench: true, speech: speech(cycle, speak, speak ? short : '', 'needs_input', 'end-turn') } } job = { ...job, awaitingConfirmation: false } if (terminal(job)) { const duplicate = cycle.reported cycle.reported = true - const text = job.status === 'error' ? '这次处理没有完成,请看电脑上的说明。' - : job.phase === 'preview_ready' ? '预览已更新,请看电脑。' : '电脑已回复,请看工作台。' - return { ...job, result: text, detailsAvailableInWorkbench: true, speech: speech(cycle, userQuery || !duplicate, userQuery || !duplicate ? text : '', duplicate ? 'already_reported' : job.phase) } + // Speak the answer itself, not a pointer to the screen; the full report stays in the workbench. + const summary = spokenReply(job.result) + const fallback = job.status === 'error' ? '这次没做成,看电脑。' : '做好了,看电脑。' + const text = summary || fallback + return { ...job, result: text, detailsAvailableInWorkbench: true, speech: speech(cycle, userQuery || !duplicate, userQuery || !duplicate ? text : '', duplicate ? 'already_reported' : job.phase, 'end-turn') } } - if (userQuery) return { ...job, speech: speech(cycle, true, '还在处理,完成后会提示你。', 'user_query') } + if (userQuery) return { ...job, speech: speech(cycle, true, '还在做。', 'user_query', 'end-turn') } const due = cycle.count < offsetsMs.length && now() - cycle.startedAt >= offsetsMs[cycle.count] if (due) { - const messages = ['收到,正在准备。', '还在准备方案,你可以继续补充要求。', '仍在处理中,接下来安静等待结果。'] - const text = accepted && cycle.count > 0 ? '已收到修改,按最新要求继续。' : messages[cycle.count] + const messages = ['收到。', '还在做。', '还在做。'] + const text = accepted && cycle.count > 0 ? '收到修改。' : messages[cycle.count] + const next = cycle.count === 0 ? 'poll' : 'end-turn' cycle.count++ - return { ...job, speech: speech(cycle, true, text, 'waiting') } + return { ...job, speech: speech(cycle, true, text, 'waiting', next) } } return { ...job, speech: speech(cycle, false, '', 'quiet_wait') } } + const ready = job => terminal(job) || (pendingQuestion(job) && !questionReported(job, cycleFor(job))) + const waitUntilReady = async (id, timeoutMs, signal) => { + if (ready(state(id))) return + const scope = AbortSignal.any([signal, lifetime.signal]) + if (scope.aborted) return + await new Promise(resolve => { + let timer + const finish = () => { clearTimeout(timer); stop(); scope.removeEventListener('abort', finish); resolve() } + timer = setTimeout(finish, timeoutMs) + const stop = delegation.subscribe(() => { if (ready(state(id))) finish() }) + scope.addEventListener('abort', finish, { once: true }) + }) + } return { receipt(id) { return report(state(id), false, true) }, + /** + * Wait briefly for this job to finish, then report it. Used so one delegate + * call can already carry the answer for short tasks. + * @param {string} id Receipt job id. + * @param {{ waitMs?: number, signal?: AbortSignal }} [options] Bound wait and caller cancellation. + * @returns {Promise} Latest speech report. + */ + async settle(id, { waitMs = settleMs, signal = new AbortController().signal } = {}) { + if (lifetime.signal.aborted) throw new Error('语音反馈服务已关闭') + const job = state(id) + if (!job) throw new Error('任务不存在') + if (waitMs > 0 && ['running', 'timeout'].includes(job.status)) { + await waitUntilReady(id, waitMs, signal) + } + return report(state(id)) + }, + /** + * Explicitly report the latest job, including a finished answer that was not + * spoken while the device was disconnected. Only a caller that asked for it + * receives an old result, so a new request never replays the previous one. + * @param {string} id Receipt job id. + * @param {{ userQuery?: boolean, signal?: AbortSignal }} [options] Explicit-query and cancellation options. + * @returns {Promise} Latest speech report. + */ async status(id, { userQuery = false, signal = new AbortController().signal } = {}) { if (lifetime.signal.aborted) throw new Error('语音反馈服务已关闭') if (signal.aborted) throw new Error('语音状态查询已取消') let job = state(id) - const ready = job => terminal(job) || (pendingQuestion(job) && !questionReported(job, cycleFor(job))) if (!ready(job) && !userQuery) { const scope = AbortSignal.any([signal, lifetime.signal]) if (!scope.aborted) await new Promise(resolve => { @@ -85,3 +174,5 @@ export function createVoiceFeedback({ delegation, offsetsMs, pollWaitMs, now = D close() { lifetime.abort() }, } } + + diff --git a/internal/xiaozhi/voice-policy.test.mjs b/internal/xiaozhi/voice-policy.test.mjs index c038b765995..ae7ec755115 100644 --- a/internal/xiaozhi/voice-policy.test.mjs +++ b/internal/xiaozhi/voice-policy.test.mjs @@ -1,7 +1,7 @@ import { test } from 'node:test' import assert from 'node:assert/strict' import { createDelegation } from './delegation.mjs' -import { createVoiceFeedback } from './voice-feedback.mjs' +import { createVoiceFeedback, spokenReply } from './voice-feedback.mjs' import { handleMessage } from './bridge.mjs' function fixture() { @@ -78,11 +78,16 @@ test('three wait hints cover the whole amendment cycle; automatic completion is const feedback = createVoiceFeedback({ delegation: f.delegation, offsetsMs: [0, 15, 45], pollWaitMs: 1, now: () => now }) try { const first = await f.delegation.submit('3 repeats'); f.claim(0) - assert.equal(feedback.receipt(first.jobId).speech.waitingCount, 1) + const receipt = feedback.receipt(first.jobId) + assert.equal(receipt.speech.waitingCount, 1) + assert.equal(receipt.speech.next, 'poll') now = 14 assert.equal((await feedback.status(first.jobId)).speech.speak, false) now = 15 - assert.equal((await feedback.status(first.jobId)).speech.waitingCount, 2) + const waiting = await feedback.status(first.jobId) + assert.equal(waiting.speech.waitingCount, 2) + assert.equal(waiting.speech.next, 'end-turn') + assert.match(waiting.speech.instruction, /结束本轮/) const latest = await f.delegation.submit('4 repeats'); f.claim(1) assert.equal(feedback.receipt(latest.jobId).speech.speak, false) now = 45 @@ -96,9 +101,10 @@ test('three wait hints cover the whole amendment cycle; automatic completion is f.delegation.captureIntent(latest.sessionId).previewReady({ id: 'e', revision: 4 }) f.end(1, 'a very long assistant explanation') const completed = await feedback.status(latest.jobId) - assert.equal(completed.speech.text, '预览已更新,请看电脑。') + assert.equal(completed.speech.text, 'a very long assistant explanation') assert.equal(completed.result, completed.speech.text) assert.equal(completed.speech.speak, true) + assert.equal(completed.speech.next, 'end-turn') assert.equal((await feedback.status(latest.jobId)).speech.speak, false) const next = await f.delegation.submit('another task') assert.equal(feedback.receipt(next.jobId).speech.waitingCount, 1) @@ -120,6 +126,56 @@ test('explicit progress questions are answered without resetting the automatic s } finally { feedback.close(); f.delegation.close() } }) +test('spoken replies carry the answer itself, stripped of report formatting', () => { + assert.equal(spokenReply('确认了:磁力架在 C3,但台面配置缺 C3 落点。细节见下。'), '确认了:磁力架在 C3,但台面配置缺 C3 落点。详情看电脑。') + assert.equal(spokenReply('## 标题\n\n- **第一点**:成功\n- 第二点:失败\n'), '标题 第一点:成功 第二点:失败') + assert.equal(spokenReply('第一句。第二句不应朗读。'), '第一句。详情看电脑。') + assert.equal(spokenReply('| a | b |\n|---|---|\n| 1 | 2 |\n\n移动完成。'), '移动完成。') + assert.equal(spokenReply('```\ncode only\n```'), '') + assert.equal(spokenReply(''), '') + const long = spokenReply('第一句说明这次搬运没有发生,因为台面配置缺少 C3 的落点区域,需要在触屏重新设置一次磁力架并保存。第二句补充很多细节。') + assert.ok(long.length <= 120) + assert.match(long, /详情看电脑/) +}) + +test('one delegate call can already return the finished answer', async () => { + const f = fixture() + const feedback = createVoiceFeedback({ delegation: f.delegation, offsetsMs: [0, 15, 45], pollWaitMs: 1, settleMs: 40 }) + const delegation = { ...f.delegation, voiceReceipt: feedback.receipt, voiceStatus: feedback.status, + voiceSettle: (id, options) => feedback.settle(id, options) } + const call = name => handleMessage({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: { message: '帮我把 C2 的板子搬到 C3' } } }, {}, null, delegation) + try { + const pending = call('moss_delegate') + await new Promise(resolve => setImmediate(resolve)) + f.claim(0) + f.end(0, '确认了:磁力架在 C3,但台面配置缺少 C3 落点,板子没有移动。') + const answer = JSON.parse((await pending).result.content[0].text) + assert.equal(answer.status, 'completed') + assert.equal(answer.speech.speak, true) + assert.equal(answer.speech.text, '确认了:磁力架在 C3,但台面配置缺少 C3 落点,板子没有移动。') + } finally { feedback.close(); f.delegation.close() } +}) + +test('a new request never replays the previous answer, but an explicit progress query still reports it', async () => { + const f = fixture() + const feedback = createVoiceFeedback({ delegation: f.delegation, offsetsMs: [0, 15, 45], pollWaitMs: 1, settleMs: 0 }) + const delegation = { ...f.delegation, voiceReceipt: feedback.receipt, voiceStatus: feedback.status, + voiceSettle: (id, options) => feedback.settle(id, options) } + const call = (id, message) => handleMessage({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'moss_delegate', arguments: { message } } }, {}, null, delegation) + const status = id => handleMessage({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'moss_task_status', arguments: { jobId: id } } }, {}, null, delegation) + try { + const first = JSON.parse((await call(1, '设计一个实验')).result.content[0].text) + f.claim(0) + f.end(0, '第一件事已经完成:协议已通过本地模拟。') + const second = JSON.parse((await call(2, '再改一下体积')).result.content[0].text) + assert.equal(second.previousSpeech, undefined) + assert.equal(second.speech.speak, true) + const old = JSON.parse((await status(first.jobId)).result.content[0].text) + assert.equal(old.speech.text, '第一件事已经完成:协议已通过本地模拟。') + assert.equal(old.speech.next, 'end-turn') + } finally { feedback.close(); f.delegation.close() } +}) + test('cancelling a status watch removes its subscription without cancelling the actual task', async () => { const f = fixture() let subscriptions = 0 @@ -154,6 +210,7 @@ test('a clarification focuses once and finishes as needs_input rather than a pre assert.equal(heard.status, 'running') assert.equal(heard.awaitingConfirmation, true) assert.equal(heard.speech.text, '每孔最终体积是多少?') + assert.equal(heard.speech.next, 'end-turn') assert.equal(heard.speech.waitingCount, 1) assert.equal(silent.speech.speak, false) f.delegation.captureIntent(accepted.sessionId).needsInput('每孔最终体积是多少?') @@ -182,6 +239,20 @@ test('a long clarification is condensed before it is spoken', async () => { } finally { feedback.close(); f.delegation.close() } }) +test('the workbench voice question names only the missing facts', async () => { + const f = fixture() + const feedback = createVoiceFeedback({ delegation: f.delegation, offsetsMs: [0, 15, 45], pollWaitMs: 10000 }) + try { + const accepted = await f.delegation.submit('missing conditions'); f.claim(0) + const long = '请提供这个新实验的必要信息:机器型号是 Flex 还是 OT-2,源板、目标板、枪头盒放哪个槽位,源液是什么,每孔转移多少微升。' + f.delegation.captureIntent(accepted.sessionId).needsInput(long, '还需要:目标板孔位、每孔体积') + const heard = await feedback.status(accepted.jobId) + assert.equal(heard.speech.text, '还需要:目标板孔位、每孔体积') + assert.equal(heard.question, '还需要:目标板孔位、每孔体积') + assert.equal(heard.speech.next, 'end-turn') + } finally { feedback.close(); f.delegation.close() } +}) + test('voice answers follow the original experiment even when the caller sets the new-task flag', async () => { const f = fixture() const feedback = createVoiceFeedback({ delegation: f.delegation, offsetsMs: [0, 15, 45], pollWaitMs: 1 }) @@ -278,3 +349,5 @@ test('an already captured voice publication can finish after its final reply was assert.deepEqual(f.delegation.get(accepted.jobId).preview, { id: 'e', revision: 3 }) } finally { f.delegation.close() } }) + + diff --git a/moss-model.patch.yml b/moss-model.patch.yml index ac3a8dd5e86..8b93513019e 100644 --- a/moss-model.patch.yml +++ b/moss-model.patch.yml @@ -48,9 +48,11 @@ agentPreset: moss-experiment bindingPath: !!js "process.env.DSH_HOME + '/xiaozhi-session.json'" workspacePath: !!js process.cwd() + diagnosticsPath: !!js "process.env.DSH_HOME + '/xiaozhi-diagnostics.jsonl'" feedback: offsetsMs: [0, 15000, 45000] pollWaitMs: 4000 + settleMs: 0 transport: reconnectMinMs: 1000 reconnectMaxMs: 30000 @@ -74,6 +76,8 @@ config: prefix: >- You are the laboratory experiment assistant. Respond briefly in the user's language. + A message prefixed 来自小智的委派 arrived here from the voice device: answer with one to three short spoken sentences, never tables, long lists or large code blocks; make the first sentence a self-contained conclusion of at most 30 characters and put details after it; answer a simple echo or connectivity test directly without tools; when a question is needed, call request_experiment_input with one short grouped question plus voice_question naming only the missing facts in at most 30 characters. + In voice tasks prefer the workbench experiment tools (create/update/analyze/get_experiment, request_experiment_input, get_robot_status) and add the extra LabscriptAI checks only when the task truly needs them, so the turn ends quickly. For a simple echo or connectivity test, respond directly. While preparing, accept amendments. Preserve confirmed conditions and the same experiment ID. When essential conditions are missing, call request_experiment_input with one grouped question and wait. From 50270ecdc490ba7bcf5d228f8a10348dec050b3c Mon Sep 17 00:00:00 2001 From: Ian <96117378+zhangyuian@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:53:25 +0800 Subject: [PATCH 3/5] Show captured deck photos in the workbench capture_image and deck_vision_check results now carry a photoMarkdown or annotatedMarkdown line built from the absolute host path. The experiment prompt tells the assistant to place that line in its reply, so the chat renders the photo through the authenticated file route instead of leaving the operator with a bare local path. --- internal/experiment/plugin-client.mjs | 27 +++++++++++++++++-- .../experiment/tests/plugin-runtime.test.mjs | 11 +++++++- moss-model.patch.yml | 1 + 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/internal/experiment/plugin-client.mjs b/internal/experiment/plugin-client.mjs index 695e2fb0950..19dc4b67a01 100644 --- a/internal/experiment/plugin-client.mjs +++ b/internal/experiment/plugin-client.mjs @@ -68,13 +68,27 @@ async function prepareExperimentArguments(workspace, directory, name, args, prot return input } +/** + * One Markdown image line the chat rewrites through its authenticated file + * route. The client maps an absolute destination to `api/file?path=…`, so the + * reply only needs the host path; the angle-bracket form keeps spaces literal. + * @param {string} alt Image alt text. + * @param {unknown} path Absolute image path on the host. + * @returns {string|undefined} Markdown line, or undefined for an unusable path. + */ +export function photoMarkdownLine(alt, path) { + if (typeof alt !== 'string' || alt === '' || /[\\[\]]/u.test(alt)) return undefined + if (typeof path !== 'string' || path === '' || /[<>\r\n]/u.test(path)) return undefined + return `![${alt}](<${path.replaceAll('\\', '/')}>)` +} + async function photoResult(workspace, response) { const json = response.content.find(item => item.type === 'text')?.text if (!json || response.isError) return response const envelope = JSON.parse(json) if (envelope.success !== true) return response const data = envelope.data - const content = [...response.content] + const content = response.content.filter(item => item.type !== 'text') for (const path of new Set([data?.saved_to, data?.image_path, data?.annotated_image_path, data?.yolo?.annotated_image_path])) { if (typeof path !== 'string') continue const bytes = await readPluginFile(workspace, path, 12 * 1024 * 1024) @@ -83,7 +97,16 @@ async function photoResult(workspace, response) { if (!mimeType) throw new ExperimentError('PLUGIN_RESPONSE_INVALID', 'LabscriptAI returned an unsupported photo format.') content.push({ type: 'image', data: bytes.toString('base64'), mimeType }) } - return { ...response, content } + // The operator sees the photo in the workbench only through this Markdown line; + // the raw image block is unreadable to a text-only model. + const photo = photoMarkdownLine('台面照片', data?.saved_to ?? data?.image_path) + const annotated = photoMarkdownLine('台面识别标注图', data?.annotated_image_path ?? data?.yolo?.annotated_image_path) + const enriched = { ...envelope, data: { + ...data, + ...(photo === undefined ? {} : { photoMarkdown: photo }), + ...(annotated === undefined ? {} : { annotatedMarkdown: annotated }), + } } + return { ...response, content: [{ type: 'text', text: JSON.stringify(enriched) }, ...content] } } /** Create a confined MCP client for simulation, documents and configured robot operations. diff --git a/internal/experiment/tests/plugin-runtime.test.mjs b/internal/experiment/tests/plugin-runtime.test.mjs index 4d046a7330f..640d9623d74 100644 --- a/internal/experiment/tests/plugin-runtime.test.mjs +++ b/internal/experiment/tests/plugin-runtime.test.mjs @@ -7,7 +7,7 @@ import { join } from 'node:path' import { zipSync, strToU8 } from 'fflate' import { boundedResponse, ensurePluginRuntime, extractPlugin, validateLock } from '../../../scripts/labscriptai-runtime.mjs' import { findPluginUpdate } from '../../../scripts/update-labscriptai.mjs' -import { readPluginDocuments, readPluginFile } from '../plugin-client.mjs' +import { photoMarkdownLine, readPluginDocuments, readPluginFile } from '../plugin-client.mjs' const revision = 'a'.repeat(40) const checksum = bytes => createHash('sha256').update(bytes).digest('hex') @@ -133,3 +133,12 @@ test('artifact manifests reject incompatible APIs, mixed analyses and tampered b return true }) }) + + +test('photo markdown points the chat at the saved host path', () => { + assert.equal(photoMarkdownLine('台面照片', 'C:\\data\\deck.jpg'), '![台面照片]()') + assert.equal(photoMarkdownLine('台面照片', '/tmp/my deck.png'), '![台面照片]()') + assert.equal(photoMarkdownLine('台面照片', ''), undefined) + assert.equal(photoMarkdownLine('台面照片', '/tmp/a.png'), undefined) + assert.equal(photoMarkdownLine('a[1]', '/tmp/a.png'), undefined) +}) diff --git a/moss-model.patch.yml b/moss-model.patch.yml index 8b93513019e..28c851d9336 100644 --- a/moss-model.patch.yml +++ b/moss-model.patch.yml @@ -91,6 +91,7 @@ To run the saved, analyzed revision, call mcp__labscriptai__run_protocol with file_path current_protocol.py. The workbench confirmation covers supported minor automatic recovery on that run. Watch that run with mcp__labscriptai__runtime_watch after start is acknowledged. Read get_robot_run when the watch finishes to confirm the recorded outcome. Use query_history or get_robot_run for read-only status. After a disconnect use safe_next_action and check the original run before acting. Capture images and run deck vision on request or when LabscriptAI identifies a layout question. Report only checks that ran and observations actually returned. + After capture_image or deck_vision_check, place the returned photoMarkdown (or annotatedMarkdown) line verbatim as its own line in your reply, exactly once and outside code blocks, so the operator sees the photo inline in the workbench; if the line is absent, say the photo is saved but could not be shown. Do not inspect or modify application code or run shell commands. - id: robot-tools name: './internal/experiment/robot-tools.mjs' From 06a755ad798288a91239083170edccafe041e068 Mon Sep 17 00:00:00 2001 From: Ian <96117378+zhangyuian@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:53:32 +0800 Subject: [PATCH 4/5] Point the experiment assistant at custom labware definitions Third-party racks such as the PE tip boxes are custom_beta definitions the local engine cannot resolve by name. The prompt now tells the assistant to fetch the exact load name, request its full definition with labware_lookup inspect include_definition, and load it with protocol.load_labware_from_definition. --- moss-model.patch.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/moss-model.patch.yml b/moss-model.patch.yml index 28c851d9336..61c99a7b8af 100644 --- a/moss-model.patch.yml +++ b/moss-model.patch.yml @@ -86,6 +86,7 @@ Create a new experiment only on explicit request or when the session has no experiment yet. Save each draft with the MOSS experiment tools. Analyze its current revision with analyze_experiment for the workbench preview. In LabscriptAI file_path and protocol_path arguments, current_protocol.py refers to the saved experiment in this conversation. + For third-party labware such as PE tip racks, call labware_lookup (action validate) to get the exact load name, then call it again with action inspect and include_definition true; load that definition in the protocol with protocol.load_labware_from_definition(definition, slot), because the local engine cannot resolve a custom_beta name on its own. Follow the LabscriptAI workflow and read_labscriptai_guidance. Use its tools for device status, on-demand photos, local deck vision, additional checks, and recovery. Only an explicit request for physical operation may trigger the workbench device confirmation. An ambiguous reply is insufficient. To run the saved, analyzed revision, call mcp__labscriptai__run_protocol with file_path current_protocol.py. The workbench confirmation covers supported minor automatic recovery on that run. From 278f949be40acb48c4b873025ccd0b11cd13746f Mon Sep 17 00:00:00 2001 From: Ian <96117378+zhangyuian@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:41:39 +0800 Subject: [PATCH 5/5] Keep Xiaozhi observing, answer on demand, and follow new conversations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Voice turns now open with 实验正在准备 and keep observing for up to two minutes with short progress lines; after that the device returns to standby and a late result is reported only when the operator asks. Missed results are no longer replayed on the next delegation, clarifications lead with the workbench voice_progress summary, and status queries can omit the job id. The browser also follows a changed voice session even without a new focus event, and replies show the annotated deck photo before the plain capture. --- internal/experiment/agent-tools.mjs | 9 +- internal/xiaozhi/README.i18n.yaml | 4 +- internal/xiaozhi/README.md | 4 +- internal/xiaozhi/README.zh.md | 4 +- internal/xiaozhi/bridge.mjs | 57 +++++++-- internal/xiaozhi/bridge.test.mjs | 5 +- internal/xiaozhi/delegation.mjs | 6 +- internal/xiaozhi/delegation.test.mjs | 29 ++++- internal/xiaozhi/plugin.mjs | 4 +- internal/xiaozhi/voice-feedback.mjs | 108 ++++++++++++++---- internal/xiaozhi/voice-policy.test.mjs | 87 ++++++++++++-- moss-model.patch.yml | 11 +- .../src/client/voice-workbench.tsx | 21 ++-- .../tests/voice-workbench.client.spec.tsx | 18 ++- 14 files changed, 297 insertions(+), 70 deletions(-) diff --git a/internal/experiment/agent-tools.mjs b/internal/experiment/agent-tools.mjs index 9fb731973c9..0b70a9bd752 100644 --- a/internal/experiment/agent-tools.mjs +++ b/internal/experiment/agent-tools.mjs @@ -36,9 +36,10 @@ export function apply(ctx) { }), 'experiment-agent-tools.guidance') ctx.tools.register(defineTool({ name: 'request_experiment_input', - description: 'Ask one concise question for essential experiment details, then wait for the operator to answer. When the message came from 小智, also pass voice_question: one short spoken line naming only the missing facts, at most 30 characters, for example 还需要:目标板孔位、每孔体积。', + description: 'Ask one concise question for essential experiment details, then wait for the operator to answer. When the message came from 小智, also pass voice_progress: one short spoken sentence summarizing what is already decided (at most 30 characters), and voice_question: one short spoken line naming only the missing facts (at most 30 characters), for example voice_progress 我按默认参数先做了 and voice_question 还需要:目标板孔位、每孔体积。', parameters: { question: { type: 'string', required: true, description: 'Question in the operator’s language.' }, + voice_progress: { type: 'string', description: 'Optional spoken one-sentence summary of what is already decided, at most 30 characters.' }, voice_question: { type: 'string', description: 'Optional spoken one-liner for the voice device: only the missing facts, at most 30 characters.' }, }, output, @@ -46,10 +47,12 @@ export function apply(ctx) { if (!args.question.trim() || Buffer.byteLength(args.question) > 2000) throw new Error('A concise nonempty question is required.') const voice = typeof args.voice_question === 'string' ? args.voice_question.trim() : '' if (voice && [...voice].length > 40) throw new Error('voice_question must be at most 40 characters.') + const progress = typeof args.voice_progress === 'string' ? args.voice_progress.trim() : '' + if (progress && [...progress].length > 40) throw new Error('voice_progress must be at most 40 characters.') const intent = ctx.get('mossVoiceIntent')?.captureIntent(sessionId(exec)) intent?.assertCurrent() - intent?.needsInput(args.question, voice || undefined) - return { status: 'needs_input', question: args.question, ...(voice ? { voice_question: voice } : {}) } + intent?.needsInput(args.question, voice || undefined, progress || undefined) + return { status: 'needs_input', question: args.question, ...(voice ? { voice_question: voice } : {}), ...(progress ? { voice_progress: progress } : {}) } }, })) diff --git a/internal/xiaozhi/README.i18n.yaml b/internal/xiaozhi/README.i18n.yaml index b27b85a0e10..d93c6ae9357 100644 --- a/internal/xiaozhi/README.i18n.yaml +++ b/internal/xiaozhi/README.i18n.yaml @@ -3,5 +3,5 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write internal/xiaozhi/README.md /xiaozhi-mcp-bridge: - en: a052017f0cbc5c03 - zh: 3ca9851a474d2e44 + en: 5db4ae124cef392f + zh: 595b911b94589f99 diff --git a/internal/xiaozhi/README.md b/internal/xiaozhi/README.md index 979a840f4fc..9efab24e0b6 100644 --- a/internal/xiaozhi/README.md +++ b/internal/xiaozhi/README.md @@ -8,7 +8,7 @@ Voice delegation uses the `moss-experiment` preset named **实验助手**. Voice `moss_delegate(message, newExperiment=false)` forwards the user's words to the active experiment conversation. Supplementary conditions and parameter changes reuse that conversation; only an explicit new experiment creates another. Do not supply a session ID from the model. The deployment can choose an initial session with `sessionId`, otherwise the first request creates one in the existing workspace, or in the configured `workspacePath` when no workspace exists. The private `bindingPath` file records the active identity and navigation sequence using an atomic replacement. A subsequent message after restart uses that identity; a missing conversation or a saved coding preset is reported rather than silently replaced. Explicitly start a new experiment to adopt the experiment preset while preserving the old conversation. -`moss_task_status(jobId, userQuery=false)` observes the accepted turn. `completed` means the Agent replied, including a clarification question; it never means a robot experiment completed. A new amendment immediately supersedes the previous voice intent and steers the same conversation. Unclaimed obsolete voice inputs are removed, and obsolete analysis cannot publish a passed check or preview. A timeout or ambiguous submission stays observable. Shutdown stops observation, not the Agent. Job receipts remain memory-only. Workflows started from the Web UI in the bound conversation publish their checked preview through the same workbench. Such a view has `jobId=null`; earlier MCP job receipts remain unchanged. Publication carries its captured owner, so a late result cannot overwrite a newer voice intent. +`moss_task_status(jobId, userQuery=false)` observes the accepted turn. `completed` means the Agent replied, including a clarification question; it never means a robot experiment completed. A new amendment immediately supersedes the previous voice intent and steers the same conversation. Unclaimed obsolete voice inputs are removed, and obsolete analysis cannot publish a passed check or preview. A timeout or ambiguous submission stays observable. Shutdown stops observation, not the Agent. Job receipts remain memory-only. `jobId` may be omitted to read the latest task of the current experiment; an expired receipt returns the latest task's report instead of an error. Automatic observation keeps the received `jobId` and `userQuery=false`; only an explicit progress question sets `userQuery` true. A query while the task is running keeps observing, and the reply ends the turn only on completion, a clarification, or the final waiting acknowledgement. Workflows started from the Web UI in the bound conversation publish their checked preview through the same workbench. Such a view has `jobId=null`; earlier MCP job receipts remain unchanged. Publication carries its captured owner, so a late result cannot overwrite a newer voice intent. `moss_experiment_status(id)` reads the active delegated conversation, falling back to the configured initial session before delegation. `moss_status` reports the computer-side service, delegation availability and supported experiment tasks, not hardware readiness. It also reports `live_control`: `approval_required` when the computer can run the robot after Web confirmation, `disabled` when live control is switched off, and `unavailable` when no robot target is configured. No robot execution tool is exposed by this bridge. A delegated conversation can request a gated run through the experiment assistant's robot tools, but the protocol-analysis check and the operator's approval in the Web UI still apply; the bridge cannot bypass them. @@ -18,7 +18,7 @@ This is a single-operator deployment. The Xiaozhi endpoint does not provide a ve While an experiment question is open, **Continue on web** opens a reply form for that question. The form remains available while Xiaozhi reconnects. The authenticated POST accepts `replyTo` with the displayed job ID and returns 409 if a newer request already replaced it. -Speech decisions keep the voice channel short. The delegate receipt speaks `收到。` and asks the caller to keep polling `moss_task_status`; the later waiting acknowledgement is `还在做。` and ends the reply so the device returns to listening, because an open reply keeps the device in its speaking state and the operator cannot interrupt it. Each decision carries `next`: `poll` keeps observing, `end-turn` reads the sentence and ends the reply, and `wait` stays quiet while observation continues. A clarification speaks the workbench `voice_question` when the assistant supplied one (`request_experiment_input` accepts a one-line `voice_question` of at most 40 characters naming only the missing facts); otherwise a long question is condensed to its leading clause plus `详细问题请看电脑`, and the full question stays in the workbench. Completion speaks the first sentence of the answer, clipped to 40 characters and followed by `详情看电脑。` when the report is longer. A new request never replays the previous answer; an explicit progress query still reports a result that finished while the device was disconnected. While awaiting an answer, short voice replies such as `50 microliters` or `OT-2` stay in the current session even if marked `newExperiment=true`. The bridge also accepts `newTask` as an alias. After an answer, polling the previous receipt returns `followJobId` and stays silent. The MCP endpoint is request/response and offers no idle-device push channel. The hosted model controls actual speech, which requires device testing; `diagnosticsPath` records connection changes, tool names and speech decisions. +Speech decisions keep the voice channel short. The delegate receipt speaks `实验正在准备。`, an amended delegate receipt speaks `收到修改,正在准备。` and both ask the caller to keep polling `moss_task_status`; the waiting acknowledgements while the workbench runs are `实验还在准备。` (15 s), `实验还在准备,请稍等。` (60 s) and `实验还在准备,你可以稍后再问我。` (120 s, ending the reply). Every waiting line except the last carries `next: poll` so the device keeps observing; only completion, a clarification and the final waiting line carry `end-turn`. Each decision carries `next`: `poll` keeps observing, `end-turn` reads the sentence and ends the reply, and `wait` stays quiet while observation continues. A clarification speaks the `voice_progress` summary first and then the missing facts (`request_experiment_input` accepts `voice_progress` and `voice_question`, each at most 40 characters); without them it speaks `voice_question`, or condenses a long question to its leading clause plus `详细问题请看电脑`, while the full question stays in the workbench. Completion speaks a few leading sentences of the answer (about 80 characters) followed by `详情看电脑。` when the report is longer. A new request never replays an answer the device already heard; a completion or clarification that arrived after the device ended its turn is not announced on the next delegation either, and is reported only when the user explicitly asks for progress or the result. `moss_task_status` accepts an omitted `jobId` for the latest task of the current experiment, and an expired receipt returns the latest task's report instead of an error, so a restarted voice conversation can still report progress. An explicit progress query still reports a result that finished while the device was disconnected. While awaiting an answer, short voice replies such as `50 microliters` or `OT-2` stay in the current session even if marked `newExperiment=true`. The bridge also accepts `newTask` as an alias. After an answer, polling the previous receipt returns `followJobId` and stays silent. The MCP endpoint is request/response and offers no idle-device push channel; a result that arrives after the two-minute window is reported only when the user asks. The hosted model controls actual speech, which requires device testing; `diagnosticsPath` records connection changes, tool names and speech decisions. Run focused checks from the project root with Node 24.9 or later: diff --git a/internal/xiaozhi/README.zh.md b/internal/xiaozhi/README.zh.md index 65e65f8cd9a..ac0e33337c6 100644 --- a/internal/xiaozhi/README.zh.md +++ b/internal/xiaozhi/README.zh.md @@ -8,7 +8,7 @@ `moss_delegate(message, newExperiment=false)` 把用户原话交给当前实验会话。补充条件和修改参数复用同一会话;只有明确的新实验才另建。模型不能传入会话 ID。部署者可通过 `sessionId` 指定初始会话;未指定时首条请求使用已有工作区,尚无工作区时使用配置的 `workspacePath` 创建会话。私有 `bindingPath` 文件以原子替换保存当前会话和导航序号。重启后的下一条消息复用该身份;原会话缺失或仍使用旧编程模式时报告错误,不悄悄另建会话;明确开始新实验后采用实验模式,旧对话继续保留。 -`moss_task_status(jobId, userQuery=false)` 跟踪已接受的轮次。`completed` 只表示 Agent 已回复,包括追问,绝不表示真机实验完成。新改口立即取代旧语音要求,并引导同一会话继续处理;未被领取的旧语音输入被移除,失效分析不能发布通过记录或预览。超时或提交结果不确定时仍保留跟踪。关闭服务只停止观察,不停止网页 Agent。任务回执仅在内存中保存。绑定会话中从网页发起的工作流也通过同一工作台发布检查通过的预览,此时 `jobId=null`,已有 MCP 任务回执保持不变。确认回调捕获结果归属,迟到结果不能覆盖更新的语音要求。 +`moss_task_status(jobId, userQuery=false)` 跟踪已接受的轮次。`completed` 只表示 Agent 已回复,包括追问,绝不表示真机实验完成。新改口立即取代旧语音要求,并引导同一会话继续处理;未被领取的旧语音输入被移除,失效分析不能发布通过记录或预览。超时或提交结果不确定时仍保留跟踪。关闭服务只停止观察,不停止网页 Agent。任务回执仅在内存中保存。`jobId` 可以省略:省略时查询当前实验的最新任务;旧编号失效时返回最新任务信息,而不是错误。自动观察仍使用收到的 `jobId` 并保持 `userQuery=false`;只有用户主动问进度才把 `userQuery` 设为 true。运行中的查询(包括问进度)都继续观察,直到任务完成、追问或最后一条等待提示才结束本轮。绑定会话中从网页发起的工作流也通过同一工作台发布检查通过的预览,此时 `jobId=null`,已有 MCP 任务回执保持不变。确认回调捕获结果归属,迟到结果不能覆盖更新的语音要求。 `moss_experiment_status(id)` 查询当前语音实验会话;尚未委派时回退到部署者指定的初始会话。`moss_status` 返回电脑端服务、委派是否可用及支持的实验任务,不代表设备就绪;其中 `live_control` 为 `approval_required` 表示电脑端可在网页确认后运行真机,为 `disabled` 表示真机控制已关闭,为 `unavailable` 表示未配置机器人地址。桥接不提供真机执行工具。被委派的会话可通过实验助手的真机工具请求受控运行,但仍须通过协议分析检查并经操作员在网页确认;桥接不能绕过这些步骤。 @@ -18,7 +18,7 @@ 实验正在等你回答时,点击 **在网页继续** 即可输入回答。小智重连期间也能使用。经过认证的 POST 使用 `replyTo` 指定当前问题对应的任务;如果已有更新的请求替代这个问题,会返回 409。 -语音播报保持简短。交办回执只说“收到。”,并要求调用方继续调用 `moss_task_status`;之后的等待提示是“还在做。”,说完就结束本轮,让设备回到聆听状态,因为回复不结束,设备就一直停在说话状态,无法打断。每条播报决定带 `next`:`poll` 表示继续观察,`end-turn` 表示朗读后结束本轮,`wait` 表示保持安静并继续观察。追问优先播报工作台填写的 `voice_question`(`request_experiment_input` 可带一行最关键的缺失信息,最多 40 字);没有提供时,长问题压缩成开头一句加“详细问题请看电脑”,完整问题保留在工作台。完成时播报答复的第一句,最长 40 字,内容更长时补一句“详情看电脑。”。新要求不会重播上一条答复;只有用户明确问进度时,才会播报断线期间完成的结果。等待回答期间,像「50 微升」或「OT-2」这样的简短语音回答,即使被误标为 `newExperiment=true` 也会留在当前会话。语音桥也接受 `newTask` 别名。收到回答后,查询上一条回执会返回 `followJobId` 并保持静默。MCP 接入点是请求/响应式的,不提供空闲设备主动推送通道。实际播报由托管模型决定,仍需在设备上验证;`diagnosticsPath` 记录连接变化、工具名称和播报决定。 +语音播报保持简短。交办回执说“实验正在准备。”,修改后的交办回执说“收到修改,正在准备。”,并要求调用方继续调用 `moss_task_status`;工作台仍在处理时的等待提示依次是“实验还在准备。”(15 秒)、“实验还在准备,请稍等。”(60 秒)和“实验还在准备,你可以稍后再问我。”(120 秒,说完结束本轮)。除最后一条外,运行中的提示都带 `next: poll`,让设备继续观察;只有完成、追问和最后一条等待提示才带 `end-turn`。每条播报决定带 `next`:`poll` 表示继续观察,`end-turn` 表示朗读后结束本轮,`wait` 表示保持安静并继续观察。追问先说一句进度概括(`request_experiment_input` 的 `voice_progress`,最多 40 字),再说缺失条件(`voice_question`,最多 40 字);没有提供时,只播报 `voice_question`,或把长问题压缩成开头一句加“详细问题请看电脑”,完整问题保留在工作台。完成时用几句话概括答复开头(最长约 80 字),更长时补一句“详情看电脑。”。新要求不会重播已经播报过的答复;设备结束本轮之后才完成的结果或追问也不会在下次交办时自动补播,只有用户明确问进度或结果时才查询并播报。`moss_task_status` 的 `jobId` 可以省略,省略时查询当前实验的最新任务;旧编号失效时返回最新任务信息而不是错误,因此语音会话重新开始后也能回答进度。只有用户明确问进度时,才会播报断线期间完成的结果。等待回答期间,像「50 微升」或「OT-2」这样的简短语音回答,即使被误标为 `newExperiment=true` 也会留在当前会话。语音桥也接受 `newTask` 别名。收到回答后,查询上一条回执会返回 `followJobId` 并保持静默。MCP 接入点是请求/响应式的,不提供空闲设备主动推送通道;两分钟窗口之后的结果只在用户主动询问时播报。实际播报由托管模型决定,仍需在设备上验证;`diagnosticsPath` 记录连接变化、工具名称和播报决定。 在项目根目录使用 Node 24.9 或更高版本运行针对性测试: diff --git a/internal/xiaozhi/bridge.mjs b/internal/xiaozhi/bridge.mjs index c8af1b91332..d6cf42883a9 100644 --- a/internal/xiaozhi/bridge.mjs +++ b/internal/xiaozhi/bridge.mjs @@ -3,7 +3,7 @@ import WebSocket from 'ws' const tools = [ { name: 'moss_status', - description: '查询电脑端 MOSS 实验服务、委派能力和真机运行模式。live_control=approval_required 表示可让电脑端实验助手经网页确认后运行真机,语音端不能直接启动;该状态不代表机器人已就绪。', + description: '查询电脑端 MOSS 实验服务、委派能力和真机运行模式。live_control=approval_required 表示可让电脑端实验助手经网页确认后运行真机,语音端不能直接启动;该状态不代表机器人已就绪。用户问实验进度或结果时改用 moss_task_status(jobId 可省略)。', inputSchema: { type: 'object', properties: {}, additionalProperties: false }, }, { @@ -18,13 +18,13 @@ const tools = [ }, { name: 'moss_delegate', - description: '把用户原话交给电脑上的当前实验助手。生成中改口也立即提交,最新要求覆盖旧要求。仅明确另开实验才设 newExperiment=true(也接受 newTask 别名)。严格按返回的 speech.speak/text 播报一次,然后按 speech.next 行动:poll 时继续调用 moss_task_status 观察;end-turn 时朗读后立即结束本轮回复、不再调用任何工具,让设备回到聆听状态;wait 时保持安静继续观察。最多 3 次等待提示。用户提出新要求时先处理这个新要求,不要先回答之前的问题;旧任务的完成结果只在用户明确问进度时朗读。返回里的 result 和 question 是给电脑端看的提示,不要朗读。awaitingConfirmation=true 时朗读问题后结束本轮,等用户回答后再调用本工具。', + description: '把用户原话交给电脑上的当前实验助手。生成中改口也立即提交,最新要求覆盖旧要求。仅明确另开实验才设 newExperiment=true(也接受 newTask 别名)。严格按返回的 speech.speak/text 播报一次,然后按 speech.next 行动:poll 时继续调用 moss_task_status 观察、不要结束本轮;end-turn 时朗读后立即结束本轮回复、不再调用任何工具,让设备回到聆听状态;wait 时保持安静继续观察。最多 4 次等待提示。用户提出新要求时先处理这个新要求,不要先回答之前的问题;旧任务的完成结果只在用户明确问进度时朗读。返回里的 result 和 question 是给电脑端看的提示,不要朗读。awaitingConfirmation=true 时朗读问题后结束本轮,等用户回答后再调用本工具。', inputSchema: { type: 'object', properties: { newExperiment: { type: 'boolean', description: '仅当用户明确要求另开新实验时为 true,普通补充和修改保持 false。' }, newTask: { type: 'boolean', description: '兼容旧调用方的别名。新调用使用 newExperiment。' }, message: { type: 'string', minLength: 1, maxLength: 8000, description: '用户提出的完整任务和已知实验条件。' } }, required: ['message'], additionalProperties: false }, }, { name: 'moss_task_status', - description: '持续观察 MOSS 任务。只在 speech.speak=true 时朗读 speech.text 一次;先看 speech.next:poll 时继续调用本工具,end-turn 时朗读后立即结束本轮回复让设备聆听,wait 时保持安静继续查询,不要因为暂时没有播报就停止。遇 followJobId 改查最新任务;用户改口立即改调 moss_delegate。completed/error 后只说指定短句,不读 result、question、JSON 或复述方案。仅用户主动问进度时设 userQuery=true。', - inputSchema: { type: 'object', properties: { jobId: { type: 'string', minLength: 1, maxLength: 128 }, userQuery: { type: 'boolean', description: '只有用户明确询问当前进度才为true,自动观察必须false。' } }, required: ['jobId'], additionalProperties: false }, + description: '持续观察 MOSS 任务。拿到任务编号后,自动观察时始终传 jobId;只在没有编号、编号失效或用户直接问进度时省略 jobId(省略时查询当前实验的最新任务)。只在 speech.speak=true 时朗读 speech.text 一次;先看 speech.next:poll 时继续调用本工具观察、不要结束本轮,end-turn 时朗读后立即结束本轮回复让设备聆听,wait 时保持安静继续查询,不要因为暂时没有播报就停止。运行中(包括用户问进度)一般返回 poll,只有完成、追问或最后一条等待提示才返回 end-turn。只有用户主动问进度才设 userQuery=true,自动观察必须保持 false。遇 followJobId 改查最新任务;用户改口立即改调 moss_delegate。completed/error 后只说指定短句,不读 result、question、JSON 或复述方案。', + inputSchema: { type: 'object', properties: { jobId: { type: 'string', minLength: 1, maxLength: 128, description: '电脑端任务编号;自动观察时始终传入,省略时查询当前实验的最新任务。' }, userQuery: { type: 'boolean', description: '只有用户明确询问当前进度才为true,自动观察必须false。' } }, additionalProperties: false }, }, ] @@ -33,6 +33,18 @@ function failure(id, code, message) { return { jsonrpc: '2.0', id, error: { code function text(value, isError = false) { return { content: [{ type: 'text', text: JSON.stringify(value) }], ...(isError ? { isError: true } : {}) } } +/** Spoken decision for a voice turn that has no task to observe. */ +function idleReport() { + return { status: 'idle', jobId: null, result: null, question: null, + speech: { speak: true, text: '现在没有正在准备的实验。', reason: 'idle', next: 'end-turn', + instruction: '只朗读 text 一次,然后结束本轮回复,让设备回到聆听状态。' } } +} +/** Spoken decision when the requested receipt expired and no newer task exists. */ +function expiredReport() { + return { status: 'expired', jobId: null, result: null, question: null, + speech: { speak: true, text: '之前那条任务记录已经失效了,我这边查不到结果。', reason: 'expired', next: 'end-turn', + instruction: '只朗读 text 一次,然后结束本轮回复,让设备回到聆听状态。' } } +} /** Handle an MCP JSON-RPC message using only the fixed session's read methods. * @param {unknown} message Incoming JSON value. @@ -77,11 +89,15 @@ export async function handleMessage(message, store, sessionId, delegation, conte } if (name === 'moss_delegate' || name === 'moss_task_status') { const submitting = name === 'moss_delegate' - const [key, flag, limit] = submitting ? ['message', 'newExperiment', 8000] : ['jobId', 'userQuery', 128] - if (Object.keys(args).some(arg => arg !== key && arg !== flag && !(submitting && arg === 'newTask')) || - (args[flag] !== undefined && typeof args[flag] !== 'boolean') || - (submitting && args.newTask !== undefined && (typeof args.newTask !== 'boolean' || (args.newExperiment !== undefined && args.newExperiment !== args.newTask))) || - typeof args[key] !== 'string' || !args[key].trim() || args[key].length > limit) return failure(id, -32602, 'Invalid tool arguments') + const valid = submitting + ? Object.keys(args).every(arg => ['message', 'newExperiment', 'newTask'].includes(arg)) && + (args.newExperiment === undefined || typeof args.newExperiment === 'boolean') && + (args.newTask === undefined || (typeof args.newTask === 'boolean' && (args.newExperiment === undefined || args.newExperiment === args.newTask))) && + typeof args.message === 'string' && Boolean(args.message.trim()) && args.message.length <= 8000 + : Object.keys(args).every(arg => ['jobId', 'userQuery'].includes(arg)) && + (args.userQuery === undefined || typeof args.userQuery === 'boolean') && + (args.jobId === undefined || (typeof args.jobId === 'string' && Boolean(args.jobId.trim()) && args.jobId.length <= 128)) + if (!valid) return failure(id, -32602, 'Invalid tool arguments') if (!delegation) return response(id, text({ error: '委派服务不可用。' }, true)) try { if (submitting) { @@ -94,7 +110,28 @@ export async function handleMessage(message, store, sessionId, delegation, conte const finished = settled !== null && !['running', 'timeout'].includes(settled.status) return response(id, text(finished ? { ...receipt, ...settled } : receipt)) } - return response(id, text(delegation.voiceStatus ? await delegation.voiceStatus(args.jobId, { userQuery: args.userQuery ?? false, signal: context.signal }) : delegation.get(args.jobId))) + const latestJobId = () => delegation.workbench?.().jobId ?? null + const omitted = args.jobId === undefined + // An omitted receipt must not turn an automatic poll into a progress + // question: that reply would end the turn before the answer exists. Only + // the caller's userQuery flag decides that. + const userQuery = args.userQuery ?? false + const read = async (jobId, jobIdSource = omitted ? 'latest' : 'explicit') => delegation.voiceStatus + ? await delegation.voiceStatus(jobId, { userQuery, signal: context.signal, jobIdSource }) + : delegation.get(jobId) + let jobId = args.jobId + if (omitted) { + jobId = latestJobId() + if (!jobId) return response(id, text(idleReport())) + } + try { + return response(id, text(await read(jobId))) + } catch { + if (omitted) throw new Error('任务记录不可读') + const latest = latestJobId() + if (!latest || latest === jobId) return response(id, text(expiredReport())) + return response(id, text({ ...await read(latest, 'fallback'), note: '旧任务记录已失效,以下是最新任务。' })) + } } catch (error) { return response(id, text({ error: String(error.message).slice(0, 300) }, true)) } diff --git a/internal/xiaozhi/bridge.test.mjs b/internal/xiaozhi/bridge.test.mjs index 347d4b14b4e..8212da24d95 100644 --- a/internal/xiaozhi/bridge.test.mjs +++ b/internal/xiaozhi/bridge.test.mjs @@ -38,9 +38,12 @@ test('the voice tool contract releases the device to listen after an end-turn de const byName = new Map(listing.result.tools.map(tool => [tool.name, tool.description])) assert.match(byName.get('moss_delegate'), /speech\.next/) assert.match(byName.get('moss_delegate'), /end-turn/) - assert.match(byName.get('moss_delegate'), /最多 3 次等待提示/) + assert.match(byName.get('moss_delegate'), /最多 4 次等待提示/) assert.match(byName.get('moss_task_status'), /end-turn/) assert.match(byName.get('moss_task_status'), /让设备聆听/) + assert.match(byName.get('moss_task_status'), /自动观察时始终传 jobId/) + const statusTool = listing.result.tools.find(tool => tool.name === 'moss_task_status') + assert.equal('required' in statusTool.inputSchema, false) }) test('reports live-control modes without exposing the robot address', async () => { diff --git a/internal/xiaozhi/delegation.mjs b/internal/xiaozhi/delegation.mjs index 97438501f78..4aab9e82881 100644 --- a/internal/xiaozhi/delegation.mjs +++ b/internal/xiaozhi/delegation.mjs @@ -37,7 +37,7 @@ export function createDelegation({ controller, workspaces, events, timeoutMs = 3 } const changed = () => { for (const listener of subscribers) { try { listener() } catch { console.warn('xiaozhi task observer failed') } } } const focus = reason => { focusSequence = Math.max(focusSequence + 1, Date.now()); focusReason = reason } - const publicJob = job => ({ jobId: job.jobId, sessionId: job.sessionId, status: job.status, result: job.result, cycleId: job.cycleId, phase: job.phase, question: job.question, voiceQuestion: job.voiceQuestion ?? null, preview: job.preview, supersededBy: job.supersededBy, ...(job.followJobId ? { followJobId: job.followJobId } : {}) }) + const publicJob = job => ({ jobId: job.jobId, sessionId: job.sessionId, status: job.status, result: job.result, cycleId: job.cycleId, phase: job.phase, question: job.question, voiceQuestion: job.voiceQuestion ?? null, voiceProgress: job.voiceProgress ?? null, preview: job.preview, supersededBy: job.supersededBy, source: job.source, ...(job.followJobId ? { followJobId: job.followJobId } : {}) }) async function admit(message, { newExperiment, source, replyTo }) { if (closed) throw new Error('委派服务已关闭') @@ -51,7 +51,7 @@ export function createDelegation({ controller, workspaces, events, timeoutMs = 3 const replacing = active(previous) if (jobs.size >= 100) jobs.delete(jobs.keys().next().value) const jobId = randomUUID() - const job = { jobId, status: 'running', sessionId: null, result: null, cycleId: replacing && !newExperiment ? previous.cycleId : jobId, phase: 'preparing', question: null, preview: null, supersededBy: null, claimed: false } + const job = { jobId, status: 'running', sessionId: null, result: null, cycleId: replacing && !newExperiment ? previous.cycleId : jobId, source: source ?? null, phase: 'preparing', question: null, voiceQuestion: null, voiceProgress: null, preview: null, supersededBy: null, claimed: false } jobs.set(jobId, job) let stopClaim, stopEvent, stopDiscard, timer let promptStarted = false, observing = true, observationClosed = false @@ -164,7 +164,7 @@ export function createDelegation({ controller, workspaces, events, timeoutMs = 3 } return { assertCurrent, - needsInput: (question, voiceQuestion) => publish('needs_input', { question, ...(typeof voiceQuestion === 'string' && voiceQuestion.trim() ? { voiceQuestion: voiceQuestion.trim() } : {}) }), + needsInput: (question, voiceQuestion, voiceProgress) => publish('needs_input', { question, ...(typeof voiceQuestion === 'string' && voiceQuestion.trim() ? { voiceQuestion: voiceQuestion.trim() } : {}), ...(typeof voiceProgress === 'string' && voiceProgress.trim() ? { voiceProgress: voiceProgress.trim() } : {}) }), previewReady: ({ id, revision }) => publish('preview_ready', { preview: { id, revision } }), } }, diff --git a/internal/xiaozhi/delegation.test.mjs b/internal/xiaozhi/delegation.test.mjs index 3a7c63d7e81..942c6a7d9a1 100644 --- a/internal/xiaozhi/delegation.test.mjs +++ b/internal/xiaozhi/delegation.test.mjs @@ -2,6 +2,7 @@ import { test } from 'node:test' import assert from 'node:assert/strict' import { createDelegation } from './delegation.mjs' import { handleMessage } from './bridge.mjs' +import { createVoiceFeedback } from './voice-feedback.mjs' function fixture({ timeoutMs = 10000, overrides = {}, failListener } = {}) { const listeners = new Map() @@ -190,11 +191,35 @@ test('MCP delegates and reports task errors without accepting a session argument const accepted = JSON.parse(reply.result.content[0].text) assert.equal(accepted.sessionId, 'session-1') assert.equal((await call(2, 'moss_delegate', { message: 'x', sessionId: 'other' })).error.code, -32602) - const error = await call(3, 'moss_task_status', { jobId: 'unknown' }) - assert.equal(error.result.isError, true) + const expired = await call(3, 'moss_task_status', { jobId: 'unknown' }) + const fallback = JSON.parse(expired.result.content[0].text) + assert.equal(expired.result.isError, undefined) + assert.equal(fallback.note, '旧任务记录已失效,以下是最新任务。') + assert.equal(fallback.jobId, accepted.jobId) } finally { f.delegation.close() } }) +test('MCP task status resolves the latest task when the caller omits its receipt', async () => { + const f = fixture() + const store = { getForSession() {}, getChecksForSession() {} } + const feedback = createVoiceFeedback({ delegation: f.delegation, offsetsMs: [0, 15, 45], pollWaitMs: 1, now: () => 0 }) + const delegation = { ...f.delegation, voiceReceipt: feedback.receipt, voiceStatus: feedback.status } + try { + const call = (id, name, args) => handleMessage({ jsonrpc: '2.0', id, method: 'tools/call', params: { name, arguments: args } }, store, null, delegation) + const idle = JSON.parse((await call(1, 'moss_task_status', {})).result.content[0].text) + assert.equal(idle.status, 'idle') + assert.equal(idle.speech.text, '现在没有正在准备的实验。') + const accepted = JSON.parse((await call(2, 'moss_delegate', { message: '模拟实验' })).result.content[0].text) + const quiet = JSON.parse((await call(3, 'moss_task_status', {})).result.content[0].text) + assert.equal(quiet.jobId, accepted.jobId) + assert.equal(quiet.status, 'running') + assert.equal(quiet.speech.speak, false) + const asked = JSON.parse((await call(4, 'moss_task_status', { userQuery: true })).result.content[0].text) + assert.equal(asked.jobId, accepted.jobId) + assert.equal(asked.speech.text, '实验正在准备。') + } finally { feedback.close(); f.delegation.close() } +}) + test('a stopped turn reports its outcome in plain language', async () => { const f = fixture() diff --git a/internal/xiaozhi/plugin.mjs b/internal/xiaozhi/plugin.mjs index c921c8cc2fe..87335366a5a 100644 --- a/internal/xiaozhi/plugin.mjs +++ b/internal/xiaozhi/plugin.mjs @@ -54,7 +54,7 @@ export function apply(ctx, config) { const current = delegation.workbench() if (current.focusSequence > seenFocus) { seenFocus = current.focusSequence; void wakeup.wake().then(reportWake) } }) - const recordSpeech = result => { record({ kind: 'speech_decision', jobId: result.jobId, cycleId: result.cycleId, phase: result.phase, speak: result.speech.speak, reason: result.speech.reason, waitingCount: result.speech.waitingCount, at: Date.now() }); return result } + const recordSpeech = (result, options) => { record({ kind: 'speech_decision', jobId: result.jobId, cycleId: result.cycleId, phase: result.phase, speak: result.speech.speak, reason: result.speech.reason, waitingCount: result.speech.waitingCount, userQuery: options?.userQuery === true, jobIdSource: options?.jobIdSource ?? 'explicit', at: Date.now() }); return result } const workbench = { ...delegation, async submit(message, options) { @@ -63,7 +63,7 @@ export function apply(ctx, config) { return receipt }, voiceReceipt: id => recordSpeech(feedback.receipt(id)), - voiceStatus: async (id, options) => recordSpeech(await feedback.status(id, options)), + voiceStatus: async (id, options) => recordSpeech(await feedback.status(id, options), options), voiceSettle: async (id, options) => recordSpeech(await feedback.settle(id, options)), workbench() { return { ...delegation.workbench(), connection: disconnect?.snapshot() ?? { status: 'not_configured', registered: false, reconnects: 0, lastCall: null }, wakeup: wakeup.state(), speechPolicy: feedback.snapshot() } diff --git a/internal/xiaozhi/voice-feedback.mjs b/internal/xiaozhi/voice-feedback.mjs index 3acbc6708ac..985095dca86 100644 --- a/internal/xiaozhi/voice-feedback.mjs +++ b/internal/xiaozhi/voice-feedback.mjs @@ -1,15 +1,11 @@ -/** Bound automatic speech across one task and its amendments; result queries stay cancellable. */ +/** Bound automatic speech across one task, its amendments, and a completion the device missed; result queries stay cancellable. */ -/** - * Render one assistant reply as a single short spoken sentence. Markdown tables, - * code fences, links and headings are dropped, then the first sentence is kept - * and clipped to the spoken limit so a voice turn never reads a report aloud. - * @param {unknown} value Assistant reply text. - * @param {{ limit?: number }} [options] Maximum spoken length before clipping. - * @returns {string} Spoken summary, or an empty string when nothing speakable remains. - */ -export function spokenReply(value, { limit = 40 } = {}) { - const text = String(value ?? '') +/** Spoken line shown when the workbench must release the device without a result. */ +const RELEASE_LINE = '实验还在准备,你可以稍后再问我。' + +/** Strip Markdown, links and code so a value can be read aloud. */ +function plainText(value) { + return String(value ?? '') .replace(/\r\n?/g, '\n') .replace(/```[\s\S]*?```/g, ' ') .replace(/^\s*\|.*$/gm, ' ') @@ -20,6 +16,53 @@ export function spokenReply(value, { limit = 40 } = {}) { .replace(/[#>`*_~]+/g, '') .replace(/\s+/g, ' ') .trim() +} + +/** Keep up to a few leading sentences within a character budget, for a completion summary. */ +export function spokenSummary(value, { limit = 80, sentences = 3 } = {}) { + const text = plainText(value) + if (!text) return '' + const chunks = text.match(/[^。!?!?]*[。!?!?]/g) + if (!chunks || chunks.length === 0) return spokenReply(text, { limit }) + const kept = [] + let total = 0 + for (const raw of chunks) { + const head = raw.replace(/[。!?!?,、,;;::]+$/, '').trim() + if (!head) continue + if (kept.length >= sentences) break + const room = limit - total + if (room <= 0) break + if (head.length <= room) { kept.push(head); total += head.length + 1 } + else { kept.push(head.slice(0, room).replace(/[,、,;;::]$/, '')); total = limit; break } + } + if (kept.length === 0) return spokenReply(text, { limit }) + const result = kept.join('。') + '。' + const more = result.length < text.length + return more ? `${result.replace(/[。!?!?]$/, '')}。详情看电脑。` : result +} + +/** Spoken line for each checkpoint; derived from the checkpoint count when not overridden. */ +function waitingMessages(offsetsMs, provided) { + if (provided) return provided + const list = ['实验正在准备。'] + for (let i = 1; i < offsetsMs.length; i++) { + if (i === offsetsMs.length - 1) list.push(RELEASE_LINE) + else if (i === 1) list.push('实验还在准备。') + else list.push('实验还在准备,请稍等。') + } + return list +} + +/** + * Render one assistant reply as a single short spoken sentence. Markdown tables, + * code fences, links and headings are dropped, then the first sentence is kept + * and clipped to the spoken limit so a voice turn never reads a report aloud. + * @param {unknown} value Assistant reply text. + * @param {{ limit?: number }} [options] Maximum spoken length before clipping. + * @returns {string} Spoken summary, or an empty string when nothing speakable remains. + */ +export function spokenReply(value, { limit = 60 } = {}) { + const text = plainText(value) if (!text) return '' const sentence = (text.match(/^[^。!?!?]*[。!?!?]/)?.[0] ?? text).trim() const head = sentence.replace(/[,、,;;::]$/, '') @@ -29,9 +72,12 @@ export function spokenReply(value, { limit = 40 } = {}) { return `${clipped.replace(/[。!?!?]$/, '')}。详情看电脑。` } -export function createVoiceFeedback({ delegation, offsetsMs, pollWaitMs, settleMs = 0, now = Date.now }) { - if (!Array.isArray(offsetsMs) || offsetsMs.length !== 3 || offsetsMs[0] !== 0 || offsetsMs.some((value, index) => !Number.isSafeInteger(value) || value < 0 || index > 0 && value <= offsetsMs[index - 1]) || !Number.isSafeInteger(pollWaitMs) || pollWaitMs < 1) throw new Error('voice feedback requires three increasing offsets beginning at zero and a positive pollWaitMs') +export function createVoiceFeedback({ delegation, offsetsMs, pollWaitMs, settleMs = 0, messages, now = Date.now }) { + if (!Array.isArray(offsetsMs) || offsetsMs.length < 2 || offsetsMs.length > 8 || offsetsMs[0] !== 0 || offsetsMs.some((value, index) => !Number.isSafeInteger(value) || value < 0 || index > 0 && value <= offsetsMs[index - 1])) throw new Error('voice feedback requires at least two increasing offsets beginning at zero') + if (!Number.isSafeInteger(pollWaitMs) || pollWaitMs < 1) throw new Error('voice feedback requires a positive pollWaitMs') + if (messages !== undefined && (!Array.isArray(messages) || messages.length !== offsetsMs.length || messages.some(value => typeof value !== 'string' || !value.trim()))) throw new Error('voice feedback messages must match the offsets and be non-empty') if (!Number.isSafeInteger(settleMs) || settleMs < 0) throw new Error('voice feedback requires a non-negative settleMs') + const waiting = waitingMessages(offsetsMs, messages) const cycles = new Map() const lifetime = new AbortController() /** @@ -60,7 +106,7 @@ export function createVoiceFeedback({ delegation, offsetsMs, pollWaitMs, settleM */ const speech = (cycle, speak, text, reason, next = 'wait') => ({ speak, text, reason, next, - waitingCount: cycle.count, waitingLimit: 3, + waitingCount: cycle.count, waitingLimit: offsetsMs.length, instruction: reason === 'needs_input' ? (speak ? '只朗读 text 一次,不加任何口头语、不复述用户原话;然后开始等用户回答;不要朗读 result 或 question 里的详细内容。' : '保持安静,等用户回答。') : next === 'poll' @@ -80,12 +126,24 @@ export function createVoiceFeedback({ delegation, offsetsMs, pollWaitMs, settleM const terminal = job => !['running', 'timeout'].includes(job.status) const pendingQuestion = job => job.phase === 'needs_input' && job.status !== 'superseded' && !job.followJobId && job.question const questionReported = (job, cycle) => cycle.question?.jobId === job.jobId && cycle.question.text === job.question + /** Spoken clarification line: a short progress summary first, then the missing facts. */ + const questionText = job => job.voiceProgress + ? job.voiceQuestion ? `${job.voiceProgress}。${job.voiceQuestion}` : job.voiceProgress + : typeof job.voiceQuestion === 'string' && job.voiceQuestion ? job.voiceQuestion : spoken(job.question) + /** + * Report one job for a voice caller. A missed completion is never replayed + * here; the caller asks for it with an explicit status query instead. + * @param {object} job Public job state. + * @param {boolean} userQuery Whether the operator asked for progress. + * @param {boolean} accepted Whether this is the receipt of a new delegation. + * @returns {object} Public report with a speech decision. + */ function report(job, userQuery = false, accepted = false) { const cycle = cycleFor(job) if (job.status === 'superseded' || job.followJobId) return { ...job, result: null, question: null, awaitingConfirmation: false, speech: speech(cycle, false, '', job.followJobId ? 'continued' : 'superseded'), followJobId: job.followJobId ?? job.supersededBy } if (pendingQuestion(job)) { const speak = userQuery || !questionReported(job, cycle) - const short = typeof job.voiceQuestion === 'string' && job.voiceQuestion ? job.voiceQuestion : spoken(job.question) + const short = questionText(job) cycle.question = { jobId: job.jobId, text: job.question } return { ...job, result: short, question: short, awaitingConfirmation: true, detailsAvailableInWorkbench: true, speech: speech(cycle, speak, speak ? short : '', 'needs_input', 'end-turn') } } @@ -94,17 +152,23 @@ export function createVoiceFeedback({ delegation, offsetsMs, pollWaitMs, settleM const duplicate = cycle.reported cycle.reported = true // Speak the answer itself, not a pointer to the screen; the full report stays in the workbench. - const summary = spokenReply(job.result) - const fallback = job.status === 'error' ? '这次没做成,看电脑。' : '做好了,看电脑。' + const summary = spokenSummary(job.result) + const fallback = job.status === 'error' ? '这次没做成,原因在电脑上。' : '已经完成了,详细结果在电脑上。' const text = summary || fallback return { ...job, result: text, detailsAvailableInWorkbench: true, speech: speech(cycle, userQuery || !duplicate, userQuery || !duplicate ? text : '', duplicate ? 'already_reported' : job.phase, 'end-turn') } } - if (userQuery) return { ...job, speech: speech(cycle, true, '还在做。', 'user_query', 'end-turn') } + if (accepted) { + // A receipt always answers the operator who just spoke; an amendment is + // acknowledged even when the next timed hint is not due yet. + const first = cycle.count === 0 + if (first) cycle.count = 1 + return { ...job, speech: speech(cycle, true, first ? waiting[0] : '收到修改,正在准备。', 'waiting', 'poll') } + } + if (userQuery) return { ...job, speech: speech(cycle, true, '实验正在准备。', 'user_query', 'poll') } const due = cycle.count < offsetsMs.length && now() - cycle.startedAt >= offsetsMs[cycle.count] if (due) { - const messages = ['收到。', '还在做。', '还在做。'] - const text = accepted && cycle.count > 0 ? '收到修改。' : messages[cycle.count] - const next = cycle.count === 0 ? 'poll' : 'end-turn' + const text = waiting[cycle.count] + const next = cycle.count === offsetsMs.length - 1 ? 'end-turn' : 'poll' cycle.count++ return { ...job, speech: speech(cycle, true, text, 'waiting', next) } } @@ -169,7 +233,7 @@ export function createVoiceFeedback({ delegation, offsetsMs, pollWaitMs, settleM snapshot() { const latest = delegation.workbench().jobId const current = latest ? cycles.get(state(latest).cycleId) : null - return { waitingCount: current?.count ?? 0, waitingLimit: 3 } + return { waitingCount: current?.count ?? 0, waitingLimit: offsetsMs.length } }, close() { lifetime.abort() }, } diff --git a/internal/xiaozhi/voice-policy.test.mjs b/internal/xiaozhi/voice-policy.test.mjs index ae7ec755115..98564467bd7 100644 --- a/internal/xiaozhi/voice-policy.test.mjs +++ b/internal/xiaozhi/voice-policy.test.mjs @@ -1,7 +1,7 @@ import { test } from 'node:test' import assert from 'node:assert/strict' import { createDelegation } from './delegation.mjs' -import { createVoiceFeedback, spokenReply } from './voice-feedback.mjs' +import { createVoiceFeedback, spokenReply, spokenSummary } from './voice-feedback.mjs' import { handleMessage } from './bridge.mjs' function fixture() { @@ -86,12 +86,17 @@ test('three wait hints cover the whole amendment cycle; automatic completion is now = 15 const waiting = await feedback.status(first.jobId) assert.equal(waiting.speech.waitingCount, 2) - assert.equal(waiting.speech.next, 'end-turn') - assert.match(waiting.speech.instruction, /结束本轮/) + assert.equal(waiting.speech.next, 'poll') + assert.match(waiting.speech.instruction, /继续/) const latest = await f.delegation.submit('4 repeats'); f.claim(1) - assert.equal(feedback.receipt(latest.jobId).speech.speak, false) + const amended = feedback.receipt(latest.jobId) + assert.equal(amended.speech.text, '收到修改,正在准备。') + assert.equal(amended.speech.waitingCount, 2) now = 45 - assert.equal((await feedback.status(latest.jobId)).speech.waitingCount, 3) + const released = await feedback.status(latest.jobId) + assert.equal(released.speech.waitingCount, 3) + assert.equal(released.speech.next, 'end-turn') + assert.match(released.speech.instruction, /结束本轮/) now = 10000 for (let i = 0; i < 65; i++) assert.equal((await feedback.status(latest.jobId)).speech.speak, false) const old = await feedback.status(first.jobId) @@ -138,6 +143,14 @@ test('spoken replies carry the answer itself, stripped of report formatting', () assert.match(long, /详情看电脑/) }) +test('completion summaries keep a few leading sentences within the budget', () => { + assert.equal(spokenSummary('第一句。第二句。第三句。'), '第一句。第二句。第三句。') + assert.equal(spokenSummary('确认了:磁力架在 C3,但台面配置缺 C3 落点。细节见下。'), '确认了:磁力架在 C3,但台面配置缺 C3 落点。细节见下。') + const clipped = spokenSummary('第一句说明这次搬运没有发生,因为台面配置缺少 C3 的落点区域,需要在触屏重新设置一次磁力架并保存。第二句补充很多细节,包括落点坐标和磁力架型号。第三句还要说明目标板孔位。') + assert.ok(clipped.length <= 120) + assert.match(clipped, /详情看电脑/) +}) + test('one delegate call can already return the finished answer', async () => { const f = fixture() const feedback = createVoiceFeedback({ delegation: f.delegation, offsetsMs: [0, 15, 45], pollWaitMs: 1, settleMs: 40 }) @@ -156,26 +169,71 @@ test('one delegate call can already return the finished answer', async () => { } finally { feedback.close(); f.delegation.close() } }) -test('a new request never replays the previous answer, but an explicit progress query still reports it', async () => { +test('a new request never replays an answer the device already heard, but an explicit progress query still reports it', async () => { const f = fixture() const feedback = createVoiceFeedback({ delegation: f.delegation, offsetsMs: [0, 15, 45], pollWaitMs: 1, settleMs: 0 }) const delegation = { ...f.delegation, voiceReceipt: feedback.receipt, voiceStatus: feedback.status, voiceSettle: (id, options) => feedback.settle(id, options) } const call = (id, message) => handleMessage({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'moss_delegate', arguments: { message } } }, {}, null, delegation) - const status = id => handleMessage({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'moss_task_status', arguments: { jobId: id } } }, {}, null, delegation) + const status = (id, args = { jobId: id }) => handleMessage({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'moss_task_status', arguments: args } }, {}, null, delegation) try { const first = JSON.parse((await call(1, '设计一个实验')).result.content[0].text) f.claim(0) f.end(0, '第一件事已经完成:协议已通过本地模拟。') + const heard = JSON.parse((await status(first.jobId)).result.content[0].text) + assert.equal(heard.speech.speak, true) const second = JSON.parse((await call(2, '再改一下体积')).result.content[0].text) assert.equal(second.previousSpeech, undefined) assert.equal(second.speech.speak, true) - const old = JSON.parse((await status(first.jobId)).result.content[0].text) + const old = JSON.parse((await status(first.jobId, { jobId: first.jobId, userQuery: true })).result.content[0].text) assert.equal(old.speech.text, '第一件事已经完成:协议已通过本地模拟。') assert.equal(old.speech.next, 'end-turn') } finally { feedback.close(); f.delegation.close() } }) +test('a missed completion is not announced on the next delegation and is reported only when asked', async () => { + const f = fixture() + const feedback = createVoiceFeedback({ delegation: f.delegation, offsetsMs: [0, 15, 45], pollWaitMs: 1, now: () => 0 }) + try { + const first = await f.delegation.submit('长时间实验', { source: 'xiaozhi' }); f.claim(0) + // The device ends its turn before the workbench answers. + f.end(0, '方案已经准备好,请在电脑上查看。') + const next = await f.delegation.submit('新的问题', { source: 'xiaozhi' }); f.claim(1) + const receipt = feedback.receipt(next.jobId) + assert.equal(receipt.previousSpeech, undefined) + assert.equal(receipt.speech.text, '实验正在准备。') + const asked = await feedback.status(first.jobId, { userQuery: true }) + assert.equal(asked.speech.text, '方案已经准备好,请在电脑上查看。') + } finally { feedback.close(); f.delegation.close() } +}) + +test('a clarification the device never heard is reported only when asked', async () => { + const f = fixture() + const feedback = createVoiceFeedback({ delegation: f.delegation, offsetsMs: [0, 15, 45], pollWaitMs: 10000, now: () => 0 }) + try { + const first = await f.delegation.submit('搬板', { source: 'xiaozhi' }); f.claim(0) + f.delegation.captureIntent(first.sessionId).needsInput('需要确认型号', '还需要:PCR板型号', '已记下:搬板') + f.end(0, '已记下:搬板。还需要:PCR板型号') + const asked = await feedback.status(first.jobId, { userQuery: true }) + assert.equal(asked.speech.text, '已记下:搬板。还需要:PCR板型号') + } finally { feedback.close(); f.delegation.close() } +}) + +test('waiting hints name the preparation instead of terse acknowledgements', async () => { + const f = fixture() + let now = 0 + const feedback = createVoiceFeedback({ delegation: f.delegation, offsetsMs: [0, 15, 45], pollWaitMs: 1, now: () => now }) + try { + const accepted = await f.delegation.submit('准备实验'); f.claim(0) + assert.equal(feedback.receipt(accepted.jobId).speech.text, '实验正在准备。') + now = 15 + assert.equal((await feedback.status(accepted.jobId)).speech.text, '实验还在准备。') + assert.equal((await feedback.status(accepted.jobId, { userQuery: true })).speech.text, '实验正在准备。') + const amended = await f.delegation.submit('再加一个条件'); f.claim(1) + assert.equal(feedback.receipt(amended.jobId).speech.text, '收到修改,正在准备。') + } finally { feedback.close(); f.delegation.close() } +}) + test('cancelling a status watch removes its subscription without cancelling the actual task', async () => { const f = fixture() let subscriptions = 0 @@ -253,6 +311,19 @@ test('the workbench voice question names only the missing facts', async () => { } finally { feedback.close(); f.delegation.close() } }) +test('a clarification speaks the progress summary before the missing facts', async () => { + const f = fixture() + const feedback = createVoiceFeedback({ delegation: f.delegation, offsetsMs: [0, 15, 45], pollWaitMs: 10000 }) + try { + const accepted = await f.delegation.submit('missing conditions'); f.claim(0) + f.delegation.captureIntent(accepted.sessionId).needsInput('请提供参数', '还需要:每孔体积', '我按默认参数先做了') + const heard = await feedback.status(accepted.jobId) + assert.equal(heard.awaitingConfirmation, true) + assert.equal(heard.speech.text, '我按默认参数先做了。还需要:每孔体积') + assert.equal(heard.speech.next, 'end-turn') + } finally { feedback.close(); f.delegation.close() } +}) + test('voice answers follow the original experiment even when the caller sets the new-task flag', async () => { const f = fixture() const feedback = createVoiceFeedback({ delegation: f.delegation, offsetsMs: [0, 15, 45], pollWaitMs: 1 }) diff --git a/moss-model.patch.yml b/moss-model.patch.yml index 61c99a7b8af..a9d2f9ecf08 100644 --- a/moss-model.patch.yml +++ b/moss-model.patch.yml @@ -50,7 +50,12 @@ workspacePath: !!js process.cwd() diagnosticsPath: !!js "process.env.DSH_HOME + '/xiaozhi-diagnostics.jsonl'" feedback: - offsetsMs: [0, 15000, 45000] + offsetsMs: [0, 15000, 60000, 120000] + messages: + - 实验正在准备。 + - 实验还在准备。 + - 实验还在准备,请稍等。 + - 实验还在准备,你可以稍后再问我。 pollWaitMs: 4000 settleMs: 0 transport: @@ -76,7 +81,7 @@ config: prefix: >- You are the laboratory experiment assistant. Respond briefly in the user's language. - A message prefixed 来自小智的委派 arrived here from the voice device: answer with one to three short spoken sentences, never tables, long lists or large code blocks; make the first sentence a self-contained conclusion of at most 30 characters and put details after it; answer a simple echo or connectivity test directly without tools; when a question is needed, call request_experiment_input with one short grouped question plus voice_question naming only the missing facts in at most 30 characters. + A message prefixed 来自小智的委派 arrived here from the voice device: answer with one to three short spoken sentences, never tables, long lists or large code blocks; make the first sentence a self-contained conclusion of at most 30 characters and put details after it; answer a simple echo or connectivity test directly without tools; when a question is needed, call request_experiment_input with one short grouped question, voice_progress naming what is already decided (at most 30 characters), and voice_question naming only the missing facts (at most 30 characters). In voice tasks prefer the workbench experiment tools (create/update/analyze/get_experiment, request_experiment_input, get_robot_status) and add the extra LabscriptAI checks only when the task truly needs them, so the turn ends quickly. For a simple echo or connectivity test, respond directly. While preparing, accept amendments. Preserve confirmed conditions and the same experiment ID. @@ -92,7 +97,7 @@ To run the saved, analyzed revision, call mcp__labscriptai__run_protocol with file_path current_protocol.py. The workbench confirmation covers supported minor automatic recovery on that run. Watch that run with mcp__labscriptai__runtime_watch after start is acknowledged. Read get_robot_run when the watch finishes to confirm the recorded outcome. Use query_history or get_robot_run for read-only status. After a disconnect use safe_next_action and check the original run before acting. Capture images and run deck vision on request or when LabscriptAI identifies a layout question. Report only checks that ran and observations actually returned. - After capture_image or deck_vision_check, place the returned photoMarkdown (or annotatedMarkdown) line verbatim as its own line in your reply, exactly once and outside code blocks, so the operator sees the photo inline in the workbench; if the line is absent, say the photo is saved but could not be shown. + After capture_image or deck_vision_check, place the returned image lines verbatim as their own lines in your reply, outside code blocks, each exactly once: when deck_vision_check returned annotatedMarkdown (the photo with recognition boxes), put that line first and then the matching photoMarkdown (the plain photo) from the same capture; when only one image line exists, place that one. If no image line is present, say the photo is saved but could not be shown. Do not inspect or modify application code or run shell commands. - id: robot-tools name: './internal/experiment/robot-tools.mjs' diff --git a/packages/client/ui-sidebar-experiment/src/client/voice-workbench.tsx b/packages/client/ui-sidebar-experiment/src/client/voice-workbench.tsx index 81e9a5bd16a..9d4f9533bf3 100644 --- a/packages/client/ui-sidebar-experiment/src/client/voice-workbench.tsx +++ b/packages/client/ui-sidebar-experiment/src/client/voice-workbench.tsx @@ -5,14 +5,14 @@ import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type {} from './status.ts' import css from './Experiment.module.css' -type State = { sequence: number } -type Actions = { acknowledge: (draft: State, sequence: number) => void } +type State = { sequence: number; sessionId: string | null } +type Actions = { acknowledge: (draft: State, sequence: number, sessionId: string | null) => void } -/** Remember navigation receipts without taking selection away on every poll. */ +/** Remember the followed voice session and navigation receipt without taking selection away on every poll. */ export function createVoiceNavigationStore(): EngineStoreHandle { return defineStore({ - init: (): State => ({ sequence: -1 }), - actions: { acknowledge: (draft, sequence) => { draft.sequence = sequence } }, + init: (): State => ({ sequence: -1, sessionId: null }), + actions: { acknowledge: (draft, sequence, sessionId) => { draft.sequence = sequence; draft.sessionId = sessionId } }, }) } @@ -25,20 +25,23 @@ export interface VoiceNavigationInjected { export function VoiceWorkbench({ useResource, useStore, actions, navigate, reply, t }: PropsRuntime<'shell.overlay'> & PropsStore> & VoiceNavigationInjected & PropsLocale<'sidebarExperiment'>) { const resource = useResource<'voiceworkbench'>('dsh-resource://voiceworkbench/current') const sequence = useStore(state => state.sequence) + const followed = useStore(state => state.sessionId) const value = resource.value - const target = value?.status === 'idle' ? null : value?.sessionId + const target = value?.status === 'idle' ? null : value?.sessionId ?? null const accepted = value?.focusSequence ?? value?.sequence + const changedSession = target !== null && target !== followed + const focusAdvanced = accepted !== undefined && target !== null && accepted > sequence const [failed, setFailed] = useState(false) const [retry, setRetry] = useState(0) useEffect(() => { - if (!target || accepted === undefined || accepted <= sequence) return + if (!target || (!changedSession && !focusAdvanced)) return const controller = new AbortController() setFailed(false) void (async () => { for (let attempt = 0; attempt < 4 && isActive(controller.signal); attempt++) { try { await navigate(target, controller.signal) - if (isActive(controller.signal)) actions.acknowledge(accepted) + if (isActive(controller.signal)) actions.acknowledge(accepted ?? sequence, target) return } catch { if (!isActive(controller.signal)) return @@ -48,7 +51,7 @@ export function VoiceWorkbench({ useResource, useStore, actions, navigate, reply } })() return () =>{ controller.abort() } - }, [target, accepted, sequence, actions, navigate, retry]) + }, [target, accepted, sequence, changedSession, focusAdvanced, actions, navigate, retry]) return <> {failed &&
{t('voiceNavigationFailed')}
} {resource.status === 'live' && value?.phase === 'needs_input' && value.jobId && value.question && diff --git a/packages/client/ui-sidebar-experiment/tests/voice-workbench.client.spec.tsx b/packages/client/ui-sidebar-experiment/tests/voice-workbench.client.spec.tsx index d6aa9c5e577..1bb4dad4825 100644 --- a/packages/client/ui-sidebar-experiment/tests/voice-workbench.client.spec.tsx +++ b/packages/client/ui-sidebar-experiment/tests/voice-workbench.client.spec.tsx @@ -150,7 +150,7 @@ it('retries a cold catalog and cancels retry work when the overlay leaves', asyn expect(screen.queryByRole('alert')).toBeNull() view.unmount() const pending = vi.fn().mockRejectedValue(new Error('catalog pending')) - const cancelled = render( select({ sequence: -1 })} navigate={pending} />) + const cancelled = render( select({ sequence: -1, sessionId: null })} navigate={pending} />) await waitFor(() => { expect(pending).toHaveBeenCalledTimes(1) }) cancelled.unmount() await new Promise(resolve => setTimeout(resolve, 300)) @@ -175,6 +175,22 @@ it('leaves selection alone for amendments and follows only a focus event', async view.unmount() }) +it('switches when the voice session changes even without a new focus event', async () => { + const store = createVoiceNavigationStore().create() + const navigate = vi.fn(async () => {}) + let sessionId = 'first-session' + const props = { useResource: () => ({ status: 'live', value: { sequence: 1, focusSequence: 10, status: 'running', sessionId } }), + useStore: (select: (state: ReturnType) => unknown) => select(store.getSnapshot()), + actions: store.actions, navigate, t: (key: string) => key } as Parameters[0] + const view = render() + await waitFor(() => { expect(navigate).toHaveBeenCalledTimes(1) }) + sessionId = 'second-session' + view.rerender() + await waitFor(() => { expect(navigate).toHaveBeenCalledTimes(2) }) + expect(navigate).toHaveBeenLastCalledWith('second-session', expect.any(AbortSignal)) + view.unmount() +}) + it('shows a checked current preview as soon as its phase is ready and rejects stale versions', () => { let revision = 2 const props = { sessionId: 's', useTabInfo: () => ({ tab: { id: 'tab' } }), t: (key: keyof typeof zh) => zh[key],