qwen-audio-agent 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTING.md +58 -0
- package/LICENSE +201 -0
- package/NOTICE +5 -0
- package/PRIVACY.md +34 -0
- package/README.md +282 -0
- package/README_EN.md +316 -0
- package/SECURITY.md +32 -0
- package/THIRD_PARTY_NOTICES.md +26 -0
- package/cli/bin/qwenaudio.mjs +10 -0
- package/cli/package.json +13 -0
- package/cli/src/arguments.mjs +247 -0
- package/cli/src/gateway-service.mjs +386 -0
- package/cli/src/instance-lock.mjs +65 -0
- package/cli/src/launcher.mjs +217 -0
- package/cli/src/runtime.mjs +356 -0
- package/cli/src/webui.mjs +61 -0
- package/config/acp/workspace/AGENTS.md +13 -0
- package/config/codebuddy/workspace/.codebuddy/models.json +19 -0
- package/config/codebuddy/workspace/AGENTS.md +13 -0
- package/config/codex/workspace/AGENTS.md +13 -0
- package/config/frontend-agent/PROMPT.md +127 -0
- package/config/hermes/workspace/AGENTS.md +13 -0
- package/config/openclaw/openclaw.json5 +50 -0
- package/config/openclaw/workspace/AGENTS.md +9 -0
- package/config/opencode/agents/qwen-audio-agent-backend.md +65 -0
- package/config/opencode/workspace/AGENTS.md +16 -0
- package/config/qoder/workspace/AGENTS.md +16 -0
- package/docs/architecture-overview-en.png +0 -0
- package/docs/architecture-overview.png +0 -0
- package/docs/architecture.md +332 -0
- package/docs/configuration.md +386 -0
- package/docs/desktop-fluid-orb-thinking.gif +0 -0
- package/docs/desktop-goo-orb-thinking.gif +0 -0
- package/docs/qwen-audio-agent-three-layer-architecture-en.png +0 -0
- package/docs/qwen-audio-agent-three-layer-architecture.png +0 -0
- package/package.json +126 -0
- package/scripts/audit-dependencies.mjs +109 -0
- package/scripts/check-desktop-release-env.mjs +41 -0
- package/scripts/codex-acp +58 -0
- package/scripts/install-global.mjs +66 -0
- package/scripts/openclaw +194 -0
- package/scripts/openclaw-gateway +8 -0
- package/scripts/opencode-acp +6 -0
- package/scripts/opencode-server +179 -0
- package/scripts/prepare-build.mjs +38 -0
- package/scripts/release-check +182 -0
- package/scripts/set-version.mjs +133 -0
- package/scripts/start.mjs +43 -0
- package/scripts/verify-package.mjs +109 -0
- package/server/package.json +18 -0
- package/server/src/agent/acp-backend-adapter.mjs +1138 -0
- package/server/src/agent/acp-backend-profile.mjs +35 -0
- package/server/src/agent/acp-backend-session-utils.mjs +139 -0
- package/server/src/agent/acp-process-client.mjs +447 -0
- package/server/src/agent/acp-session-registry.mjs +106 -0
- package/server/src/agent/acp-session-tools.mjs +257 -0
- package/server/src/agent/agent-client.mjs +218 -0
- package/server/src/agent/backend-adapter.mjs +15 -0
- package/server/src/agent/backend-agent-instructions.mjs +8 -0
- package/server/src/agent/backends/codebuddy.mjs +47 -0
- package/server/src/agent/backends/codex.mjs +62 -0
- package/server/src/agent/backends/generic-acp.mjs +46 -0
- package/server/src/agent/backends/hermes.mjs +29 -0
- package/server/src/agent/backends/openclaw.mjs +101 -0
- package/server/src/agent/backends/opencode.mjs +36 -0
- package/server/src/agent/backends/qoder.mjs +47 -0
- package/server/src/agent/backends/registry.mjs +32 -0
- package/server/src/agent/backends/shared.mjs +46 -0
- package/server/src/agent/coordinator.mjs +308 -0
- package/server/src/agent/openclaw-adapter.mjs +245 -0
- package/server/src/app/bootstrap.mjs +244 -0
- package/server/src/conversation/conversation-sync.mjs +183 -0
- package/server/src/conversation/frontend-agent-context.mjs +162 -0
- package/server/src/conversation/frontend-memory.mjs +328 -0
- package/server/src/conversation/profiled-memory-store.mjs +87 -0
- package/server/src/conversation/task-result-projector.mjs +18 -0
- package/server/src/conversation/user-profile.mjs +234 -0
- package/server/src/core/config.mjs +388 -0
- package/server/src/core/identity.mjs +93 -0
- package/server/src/core/install-paths.mjs +8 -0
- package/server/src/core/package-version.mjs +10 -0
- package/server/src/core/request-security.mjs +80 -0
- package/server/src/index.mjs +67 -0
- package/server/src/process/backend-drivers/codebuddy.mjs +15 -0
- package/server/src/process/backend-drivers/codex.mjs +15 -0
- package/server/src/process/backend-drivers/generic-acp.mjs +18 -0
- package/server/src/process/backend-drivers/hermes.mjs +15 -0
- package/server/src/process/backend-drivers/openclaw.mjs +35 -0
- package/server/src/process/backend-drivers/opencode.mjs +75 -0
- package/server/src/process/backend-drivers/qoder.mjs +15 -0
- package/server/src/process/backend-drivers/registry.mjs +24 -0
- package/server/src/process/backend-drivers/shared.mjs +46 -0
- package/server/src/process/managed-backend.mjs +188 -0
- package/server/src/task/task-manager.mjs +704 -0
- package/server/src/task/task-scheduler.mjs +44 -0
- package/server/src/task/task-store.mjs +167 -0
- package/server/src/voice/active-voice-clients.mjs +58 -0
- package/server/src/voice/announcement/announcement-manager.mjs +402 -0
- package/server/src/voice/announcement/announcement-window.mjs +89 -0
- package/server/src/voice/input-transcript.mjs +9 -0
- package/server/src/voice/realtime-errors.mjs +6 -0
- package/server/src/voice/realtime-gateway.mjs +1366 -0
- package/server/src/voice/realtime-provider.mjs +771 -0
- package/server/src/voice/reconnect-backoff.mjs +30 -0
- package/server/src/voice/response-context.mjs +41 -0
- package/server/src/voice/session-permission-policy.mjs +56 -0
- package/server/src/voice/tools/tool-call-handler.mjs +823 -0
- package/server/src/voice/tools/turn-transcripts.mjs +59 -0
- package/server/src/voice/turn-correlation.mjs +41 -0
- package/shared/backend-catalog.mjs +56 -0
- package/shared/gateway-client.mjs +13 -0
- package/shared/realtime-events.mjs +55 -0
- package/shared/runtime-environment.mjs +422 -0
- package/tui/native/macos-voice-io.swift +552 -0
- package/tui/native/portaudio-voice-io.py +240 -0
- package/tui/package.json +13 -0
- package/tui/src/index.mjs +1217 -0
- package/tui/src/macos-voice-io.mjs +186 -0
- package/tui/src/portaudio-voice-io.mjs +158 -0
- package/web/dist/assets/index-BeamDvsE.js +38 -0
- package/web/dist/assets/index-BuB0EFih.css +1 -0
- package/web/dist/index.html +14 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { backendDriver } from './backends/registry.mjs'
|
|
2
|
+
export { endpointAvailable } from './backends/shared.mjs'
|
|
3
|
+
|
|
4
|
+
export function acpBackendProfile({
|
|
5
|
+
protocol,
|
|
6
|
+
root,
|
|
7
|
+
directory,
|
|
8
|
+
cliPath,
|
|
9
|
+
baseUrl,
|
|
10
|
+
token,
|
|
11
|
+
tokenFile,
|
|
12
|
+
coordinatorAgent,
|
|
13
|
+
configDirectory,
|
|
14
|
+
permissionMode,
|
|
15
|
+
model,
|
|
16
|
+
modelUrl,
|
|
17
|
+
args,
|
|
18
|
+
label,
|
|
19
|
+
}) {
|
|
20
|
+
return backendDriver(protocol).createProfile({
|
|
21
|
+
root,
|
|
22
|
+
directory,
|
|
23
|
+
cliPath,
|
|
24
|
+
baseUrl,
|
|
25
|
+
token,
|
|
26
|
+
tokenFile,
|
|
27
|
+
coordinatorAgent,
|
|
28
|
+
configDirectory,
|
|
29
|
+
permissionMode,
|
|
30
|
+
model,
|
|
31
|
+
modelUrl,
|
|
32
|
+
args,
|
|
33
|
+
label,
|
|
34
|
+
})
|
|
35
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
function clean(value) {
|
|
2
|
+
return String(value || '').trim()
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
function bounded(value, max = 300) {
|
|
6
|
+
return clean(value).replace(/\s+/g, ' ').slice(0, max)
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function coordinatorKey(ownerId, protocol) {
|
|
10
|
+
return `${protocol}:${encodeURIComponent(clean(ownerId) || 'personal')}:backend`
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function projectSessionKey(protocol, sessionId) {
|
|
14
|
+
return `${protocol}:${clean(sessionId)}`
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function normalizeCoordinatorContent(content) {
|
|
18
|
+
const text = clean(content)
|
|
19
|
+
const candidate = text.match(/```(?:json)?\s*([\s\S]*?)```/i)?.[1]?.trim()
|
|
20
|
+
|| text
|
|
21
|
+
try {
|
|
22
|
+
const parsed = JSON.parse(candidate)
|
|
23
|
+
const inline = parsed?.presentation?.inline
|
|
24
|
+
if (typeof inline !== 'string') return text
|
|
25
|
+
parsed.presentation.inline = clean(inline)
|
|
26
|
+
? {
|
|
27
|
+
title: 'Agent 结果',
|
|
28
|
+
format: 'markdown',
|
|
29
|
+
content: inline,
|
|
30
|
+
}
|
|
31
|
+
: null
|
|
32
|
+
return JSON.stringify(parsed)
|
|
33
|
+
} catch {
|
|
34
|
+
return text
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function coordinatorPresentation(content) {
|
|
39
|
+
const candidate = clean(content).match(
|
|
40
|
+
/```(?:json)?\s*([\s\S]*?)```/i,
|
|
41
|
+
)?.[1] || clean(content)
|
|
42
|
+
try {
|
|
43
|
+
const presentation = JSON.parse(candidate)?.presentation
|
|
44
|
+
if (!presentation || typeof presentation !== 'object') return null
|
|
45
|
+
return {
|
|
46
|
+
speech: clean(presentation.speech),
|
|
47
|
+
inline: presentation.inline && typeof presentation.inline === 'object'
|
|
48
|
+
? presentation.inline
|
|
49
|
+
: null,
|
|
50
|
+
}
|
|
51
|
+
} catch {
|
|
52
|
+
return null
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function sessionSummary(session) {
|
|
57
|
+
return {
|
|
58
|
+
session_id: clean(session?.sessionId),
|
|
59
|
+
title: bounded(session?.title, 160),
|
|
60
|
+
directory: clean(session?.cwd),
|
|
61
|
+
updated_at: clean(session?.updatedAt),
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function categoryForTool(update) {
|
|
66
|
+
const hint = [
|
|
67
|
+
update?.name,
|
|
68
|
+
update?.title,
|
|
69
|
+
JSON.stringify(update?.rawInput || {}),
|
|
70
|
+
].join(' ').toLowerCase()
|
|
71
|
+
if (/image|draw|canvas|图片|图像|绘图/.test(hint)) return 'image'
|
|
72
|
+
if (/search|web|fetch|browser|搜索|查询/.test(hint)) return 'search'
|
|
73
|
+
if (/read|glob|grep|list|读取|查找/.test(hint)) return 'read'
|
|
74
|
+
if (/write|edit|patch|写入|修改/.test(hint)) return 'write'
|
|
75
|
+
return 'run'
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function activityFromUpdate(update, known = new Map()) {
|
|
79
|
+
if (!['tool_call', 'tool_call_update'].includes(update?.sessionUpdate)) {
|
|
80
|
+
if (update?.sessionUpdate === 'agent_message_chunk') {
|
|
81
|
+
return { id: null, kind: 'text', status: 'running' }
|
|
82
|
+
}
|
|
83
|
+
return null
|
|
84
|
+
}
|
|
85
|
+
const id = clean(update.toolCallId)
|
|
86
|
+
const merged = {
|
|
87
|
+
...(known.get(id) || {}),
|
|
88
|
+
...update,
|
|
89
|
+
}
|
|
90
|
+
const activity = {
|
|
91
|
+
id: id || null,
|
|
92
|
+
kind: 'tool',
|
|
93
|
+
tool: bounded(merged.name || merged.title, 100) || 'tool',
|
|
94
|
+
status: merged.status || 'running',
|
|
95
|
+
category: categoryForTool(merged),
|
|
96
|
+
detail: bounded(
|
|
97
|
+
merged.rawInput?.description
|
|
98
|
+
|| merged.rawInput?.query
|
|
99
|
+
|| merged.rawInput?.path
|
|
100
|
+
|| merged.rawInput?.command
|
|
101
|
+
|| '',
|
|
102
|
+
),
|
|
103
|
+
}
|
|
104
|
+
if (id && ['completed', 'failed'].includes(merged.status)) known.delete(id)
|
|
105
|
+
else if (id) known.set(id, merged)
|
|
106
|
+
return activity
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function nativeToolOutput(value) {
|
|
110
|
+
if (!value) return {}
|
|
111
|
+
if (typeof value === 'string') {
|
|
112
|
+
try {
|
|
113
|
+
return nativeToolOutput(JSON.parse(value))
|
|
114
|
+
} catch {
|
|
115
|
+
return {}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (Array.isArray(value)) {
|
|
119
|
+
for (const item of value) {
|
|
120
|
+
const parsed = nativeToolOutput(item)
|
|
121
|
+
if (Object.keys(parsed).length) return parsed
|
|
122
|
+
}
|
|
123
|
+
return {}
|
|
124
|
+
}
|
|
125
|
+
if (typeof value !== 'object') return {}
|
|
126
|
+
if (
|
|
127
|
+
value.childSessionKey
|
|
128
|
+
|| value.sessionKey
|
|
129
|
+
|| value.sessionId
|
|
130
|
+
|| value.session_id
|
|
131
|
+
) return value
|
|
132
|
+
const details = nativeToolOutput(value.details)
|
|
133
|
+
if (Object.keys(details).length) return details
|
|
134
|
+
for (const block of Array.isArray(value.content) ? value.content : []) {
|
|
135
|
+
const parsed = nativeToolOutput(block?.text || block?.content || block)
|
|
136
|
+
if (Object.keys(parsed).length) return parsed
|
|
137
|
+
}
|
|
138
|
+
return {}
|
|
139
|
+
}
|
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { Readable, Writable } from 'node:stream'
|
|
3
|
+
import * as acp from '@agentclientprotocol/sdk'
|
|
4
|
+
import { PACKAGE_VERSION } from '../core/package-version.mjs'
|
|
5
|
+
import { AgentError, requestSignal } from './backend-adapter.mjs'
|
|
6
|
+
|
|
7
|
+
const MAX_STDERR_CHARS = 12_000
|
|
8
|
+
|
|
9
|
+
function clean(value) {
|
|
10
|
+
return String(value || '').trim()
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function textFromUpdate(update) {
|
|
14
|
+
if (
|
|
15
|
+
update?.sessionUpdate !== 'agent_message_chunk'
|
|
16
|
+
|| update.content?.type !== 'text'
|
|
17
|
+
) return ''
|
|
18
|
+
return String(update.content.text || '')
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function processError(label, message, stderr = '') {
|
|
22
|
+
return new AgentError(
|
|
23
|
+
`${label} ACP ${message}${stderr ? `:${stderr}` : ''}`,
|
|
24
|
+
{ protocol: 'acp' },
|
|
25
|
+
)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export class AcpProcessClient {
|
|
29
|
+
constructor({
|
|
30
|
+
label,
|
|
31
|
+
command,
|
|
32
|
+
args = [],
|
|
33
|
+
cwd,
|
|
34
|
+
env = process.env,
|
|
35
|
+
timeoutMs = 300_000,
|
|
36
|
+
spawnImpl = spawn,
|
|
37
|
+
onPermission,
|
|
38
|
+
onUpdate,
|
|
39
|
+
}) {
|
|
40
|
+
this.label = label
|
|
41
|
+
this.command = command
|
|
42
|
+
this.args = args
|
|
43
|
+
this.cwd = cwd
|
|
44
|
+
this.env = env
|
|
45
|
+
this.timeoutMs = timeoutMs
|
|
46
|
+
this.spawn = spawnImpl
|
|
47
|
+
this.onPermission = onPermission
|
|
48
|
+
this.onUpdate = onUpdate
|
|
49
|
+
this.child = null
|
|
50
|
+
this.connection = null
|
|
51
|
+
this.context = null
|
|
52
|
+
this.initializeResult = null
|
|
53
|
+
this.startPromise = null
|
|
54
|
+
this.stderr = ''
|
|
55
|
+
this.activePrompts = new Map()
|
|
56
|
+
this.sessions = new Map()
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
get capabilities() {
|
|
60
|
+
return this.initializeResult?.agentCapabilities || {}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
get agentInfo() {
|
|
64
|
+
return this.initializeResult?.agentInfo || null
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
appendStderr(chunk) {
|
|
68
|
+
this.stderr = `${this.stderr}${String(chunk || '')}`.slice(
|
|
69
|
+
-MAX_STDERR_CHARS,
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async start() {
|
|
74
|
+
if (this.startPromise) return this.startPromise
|
|
75
|
+
if (
|
|
76
|
+
this.initializeResult
|
|
77
|
+
&& this.context
|
|
78
|
+
&& this.child?.exitCode == null
|
|
79
|
+
) {
|
|
80
|
+
return this.initializeResult
|
|
81
|
+
}
|
|
82
|
+
this.startPromise = this.startProcess()
|
|
83
|
+
.finally(() => {
|
|
84
|
+
this.startPromise = null
|
|
85
|
+
})
|
|
86
|
+
return this.startPromise
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async startProcess() {
|
|
90
|
+
this.stderr = ''
|
|
91
|
+
const child = this.spawn(this.command, this.args, {
|
|
92
|
+
cwd: this.cwd,
|
|
93
|
+
env: this.env,
|
|
94
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
95
|
+
})
|
|
96
|
+
this.child = child
|
|
97
|
+
child.stderr?.on('data', chunk => this.appendStderr(chunk))
|
|
98
|
+
const stream = acp.ndJsonStream(
|
|
99
|
+
Writable.toWeb(child.stdin),
|
|
100
|
+
Readable.toWeb(child.stdout),
|
|
101
|
+
)
|
|
102
|
+
const app = acp.client({ name: 'qwen-audio-agent' })
|
|
103
|
+
.onRequest(
|
|
104
|
+
acp.methods.client.session.requestPermission,
|
|
105
|
+
context => this.handlePermission(context.params, context.signal),
|
|
106
|
+
)
|
|
107
|
+
.onNotification(
|
|
108
|
+
acp.methods.client.session.update,
|
|
109
|
+
context => this.handleUpdate(context.params),
|
|
110
|
+
)
|
|
111
|
+
const connection = app.connect(stream)
|
|
112
|
+
this.connection = connection
|
|
113
|
+
this.context = connection.agent
|
|
114
|
+
const exited = new Promise((_, reject) => {
|
|
115
|
+
child.once('error', error => reject(processError(
|
|
116
|
+
this.label,
|
|
117
|
+
`进程启动失败(${error.message})`,
|
|
118
|
+
)))
|
|
119
|
+
child.once('exit', (code, signal) => reject(processError(
|
|
120
|
+
this.label,
|
|
121
|
+
`进程意外退出(${signal || code || 'unknown'})`,
|
|
122
|
+
clean(this.stderr),
|
|
123
|
+
)))
|
|
124
|
+
})
|
|
125
|
+
// Promise.race stops observing the loser after initialization succeeds.
|
|
126
|
+
// Keep the process lifecycle rejection handled for the rest of the client.
|
|
127
|
+
exited.catch(() => {})
|
|
128
|
+
try {
|
|
129
|
+
this.initializeResult = await Promise.race([
|
|
130
|
+
this.context.request(
|
|
131
|
+
acp.methods.agent.initialize,
|
|
132
|
+
{
|
|
133
|
+
protocolVersion: acp.PROTOCOL_VERSION,
|
|
134
|
+
clientCapabilities: {},
|
|
135
|
+
clientInfo: {
|
|
136
|
+
name: 'qwen-audio-agent',
|
|
137
|
+
title: 'qwen-audio-agent Gateway',
|
|
138
|
+
version: PACKAGE_VERSION,
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
{ signal: AbortSignal.timeout(15_000) },
|
|
142
|
+
),
|
|
143
|
+
exited,
|
|
144
|
+
])
|
|
145
|
+
if (
|
|
146
|
+
this.initializeResult?.protocolVersion !== acp.PROTOCOL_VERSION
|
|
147
|
+
) {
|
|
148
|
+
throw processError(
|
|
149
|
+
this.label,
|
|
150
|
+
`协议版本不兼容(Agent=${
|
|
151
|
+
this.initializeResult?.protocolVersion
|
|
152
|
+
},Client=${acp.PROTOCOL_VERSION})`,
|
|
153
|
+
)
|
|
154
|
+
}
|
|
155
|
+
connection.closed.finally(() => {
|
|
156
|
+
if (this.connection !== connection) return
|
|
157
|
+
this.connection = null
|
|
158
|
+
this.context = null
|
|
159
|
+
this.initializeResult = null
|
|
160
|
+
}).catch(() => {})
|
|
161
|
+
return this.initializeResult
|
|
162
|
+
} catch (error) {
|
|
163
|
+
connection.close(error)
|
|
164
|
+
if (child.exitCode == null) child.kill('SIGTERM')
|
|
165
|
+
this.connection = null
|
|
166
|
+
this.context = null
|
|
167
|
+
this.initializeResult = null
|
|
168
|
+
throw error
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async handlePermission(params, signal) {
|
|
173
|
+
if (!this.onPermission) {
|
|
174
|
+
return { outcome: { outcome: 'cancelled' } }
|
|
175
|
+
}
|
|
176
|
+
const active = this.activePrompts.get(String(params.sessionId))
|
|
177
|
+
active?.pauseTimeout?.()
|
|
178
|
+
try {
|
|
179
|
+
return await this.onPermission(params, {
|
|
180
|
+
signal,
|
|
181
|
+
session: this.sessions.get(String(params.sessionId)),
|
|
182
|
+
})
|
|
183
|
+
} finally {
|
|
184
|
+
active?.resumeTimeout?.()
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
handleUpdate(notification) {
|
|
189
|
+
const sessionId = String(notification?.sessionId || '')
|
|
190
|
+
const update = notification?.update
|
|
191
|
+
if (!sessionId || !update) return
|
|
192
|
+
const active = this.activePrompts.get(sessionId)
|
|
193
|
+
const text = textFromUpdate(update)
|
|
194
|
+
if (active && text) active.text.push(text)
|
|
195
|
+
try {
|
|
196
|
+
active?.onUpdate?.(update, notification)
|
|
197
|
+
this.onUpdate?.(update, {
|
|
198
|
+
notification,
|
|
199
|
+
session: this.sessions.get(sessionId),
|
|
200
|
+
})
|
|
201
|
+
} catch {
|
|
202
|
+
// UI projection must never interrupt the ACP connection.
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
requestSignal(signal, timeoutMs = this.timeoutMs) {
|
|
207
|
+
return requestSignal(signal, timeoutMs)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async request(method, params, {
|
|
211
|
+
signal,
|
|
212
|
+
timeoutMs = this.timeoutMs,
|
|
213
|
+
} = {}) {
|
|
214
|
+
try {
|
|
215
|
+
await this.start()
|
|
216
|
+
return await this.context.request(method, params, {
|
|
217
|
+
signal: this.requestSignal(signal, timeoutMs),
|
|
218
|
+
})
|
|
219
|
+
} catch (error) {
|
|
220
|
+
if (signal?.aborted) throw signal.reason
|
|
221
|
+
throw new AgentError(
|
|
222
|
+
`${this.label} ACP ${method} 失败:${error?.message || error}${
|
|
223
|
+
this.stderr ? `:${clean(this.stderr)}` : ''
|
|
224
|
+
}`,
|
|
225
|
+
{
|
|
226
|
+
body: clean(this.stderr),
|
|
227
|
+
protocol: 'acp',
|
|
228
|
+
},
|
|
229
|
+
)
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async notify(method, params) {
|
|
234
|
+
await this.start()
|
|
235
|
+
return this.context.notify(method, params)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
rememberSession(sessionId, details = {}) {
|
|
239
|
+
const id = String(sessionId || '')
|
|
240
|
+
if (!id) return null
|
|
241
|
+
const session = {
|
|
242
|
+
...(this.sessions.get(id) || {}),
|
|
243
|
+
...details,
|
|
244
|
+
sessionId: id,
|
|
245
|
+
}
|
|
246
|
+
this.sessions.set(id, session)
|
|
247
|
+
return session
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async newSession({
|
|
251
|
+
cwd = this.cwd,
|
|
252
|
+
mcpServers = [],
|
|
253
|
+
meta,
|
|
254
|
+
ownerId,
|
|
255
|
+
role = 'project',
|
|
256
|
+
} = {}) {
|
|
257
|
+
const response = await this.request(acp.methods.agent.session.new, {
|
|
258
|
+
cwd,
|
|
259
|
+
mcpServers,
|
|
260
|
+
...(meta ? { _meta: meta } : {}),
|
|
261
|
+
})
|
|
262
|
+
return this.rememberSession(response.sessionId, {
|
|
263
|
+
cwd,
|
|
264
|
+
ownerId,
|
|
265
|
+
role,
|
|
266
|
+
mcpServers,
|
|
267
|
+
response,
|
|
268
|
+
})
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async resumeSession(sessionId, {
|
|
272
|
+
cwd = this.cwd,
|
|
273
|
+
mcpServers = [],
|
|
274
|
+
meta,
|
|
275
|
+
ownerId,
|
|
276
|
+
role = 'project',
|
|
277
|
+
} = {}) {
|
|
278
|
+
await this.start()
|
|
279
|
+
const params = {
|
|
280
|
+
sessionId: String(sessionId),
|
|
281
|
+
cwd,
|
|
282
|
+
mcpServers,
|
|
283
|
+
...(meta ? { _meta: meta } : {}),
|
|
284
|
+
}
|
|
285
|
+
const sessionCapabilities = this.capabilities.sessionCapabilities || {}
|
|
286
|
+
let response
|
|
287
|
+
if (sessionCapabilities.resume) {
|
|
288
|
+
response = await this.request(acp.methods.agent.session.resume, params)
|
|
289
|
+
} else if (this.capabilities.loadSession) {
|
|
290
|
+
response = await this.request(acp.methods.agent.session.load, params)
|
|
291
|
+
} else {
|
|
292
|
+
throw new AgentError(
|
|
293
|
+
`${this.label} ACP 不支持继续已有 Session`,
|
|
294
|
+
{ protocol: 'acp' },
|
|
295
|
+
)
|
|
296
|
+
}
|
|
297
|
+
return this.rememberSession(sessionId, {
|
|
298
|
+
cwd,
|
|
299
|
+
ownerId,
|
|
300
|
+
role,
|
|
301
|
+
mcpServers,
|
|
302
|
+
response,
|
|
303
|
+
})
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
async listSessions({ cwd, limit = 100, signal } = {}) {
|
|
307
|
+
await this.start()
|
|
308
|
+
if (!this.capabilities.sessionCapabilities?.list) return []
|
|
309
|
+
const sessions = []
|
|
310
|
+
let cursor = null
|
|
311
|
+
do {
|
|
312
|
+
const response = await this.request(
|
|
313
|
+
acp.methods.agent.session.list,
|
|
314
|
+
{
|
|
315
|
+
...(cwd ? { cwd } : {}),
|
|
316
|
+
...(cursor ? { cursor } : {}),
|
|
317
|
+
_meta: { limit: Math.min(100, Math.max(1, limit - sessions.length)) },
|
|
318
|
+
},
|
|
319
|
+
{ signal, timeoutMs: 15_000 },
|
|
320
|
+
)
|
|
321
|
+
sessions.push(...(response.sessions || []))
|
|
322
|
+
cursor = response.nextCursor || null
|
|
323
|
+
} while (cursor && sessions.length < limit)
|
|
324
|
+
return sessions.slice(0, limit)
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async prompt(sessionId, prompt, {
|
|
328
|
+
signal,
|
|
329
|
+
timeoutMs = this.timeoutMs,
|
|
330
|
+
onUpdate,
|
|
331
|
+
} = {}) {
|
|
332
|
+
const id = String(sessionId)
|
|
333
|
+
if (this.activePrompts.has(id)) {
|
|
334
|
+
throw new AgentError(
|
|
335
|
+
`${this.label} Session ${id} 已有正在执行的请求`,
|
|
336
|
+
{ status: 409, protocol: 'acp' },
|
|
337
|
+
)
|
|
338
|
+
}
|
|
339
|
+
const timeoutController = new AbortController()
|
|
340
|
+
let timeoutTimer = null
|
|
341
|
+
let permissionDepth = 0
|
|
342
|
+
const armTimeout = () => {
|
|
343
|
+
clearTimeout(timeoutTimer)
|
|
344
|
+
timeoutTimer = null
|
|
345
|
+
if (!timeoutMs || timeoutController.signal.aborted) return
|
|
346
|
+
timeoutTimer = setTimeout(() => {
|
|
347
|
+
timeoutController.abort(new DOMException(
|
|
348
|
+
'The operation was aborted due to timeout',
|
|
349
|
+
'TimeoutError',
|
|
350
|
+
))
|
|
351
|
+
}, timeoutMs)
|
|
352
|
+
timeoutTimer.unref?.()
|
|
353
|
+
}
|
|
354
|
+
const active = {
|
|
355
|
+
text: [],
|
|
356
|
+
onUpdate,
|
|
357
|
+
pauseTimeout: () => {
|
|
358
|
+
permissionDepth += 1
|
|
359
|
+
clearTimeout(timeoutTimer)
|
|
360
|
+
timeoutTimer = null
|
|
361
|
+
},
|
|
362
|
+
resumeTimeout: () => {
|
|
363
|
+
permissionDepth = Math.max(0, permissionDepth - 1)
|
|
364
|
+
if (!permissionDepth) armTimeout()
|
|
365
|
+
},
|
|
366
|
+
}
|
|
367
|
+
this.activePrompts.set(id, active)
|
|
368
|
+
const combined = signal
|
|
369
|
+
? AbortSignal.any([signal, timeoutController.signal])
|
|
370
|
+
: timeoutController.signal
|
|
371
|
+
armTimeout()
|
|
372
|
+
const cancel = () => {
|
|
373
|
+
this.notify(acp.methods.agent.session.cancel, {
|
|
374
|
+
sessionId: id,
|
|
375
|
+
}).catch(() => {})
|
|
376
|
+
}
|
|
377
|
+
combined?.addEventListener('abort', cancel, { once: true })
|
|
378
|
+
if (combined?.aborted) cancel()
|
|
379
|
+
try {
|
|
380
|
+
const response = await this.request(
|
|
381
|
+
acp.methods.agent.session.prompt,
|
|
382
|
+
{
|
|
383
|
+
sessionId: id,
|
|
384
|
+
prompt: [{ type: 'text', text: String(prompt || '') }],
|
|
385
|
+
},
|
|
386
|
+
{ signal: combined, timeoutMs: 0 },
|
|
387
|
+
)
|
|
388
|
+
const content = active.text.join('').trim()
|
|
389
|
+
if (response?.stopReason === 'cancelled') {
|
|
390
|
+
throw combined?.reason || new Error('ACP Session 已取消')
|
|
391
|
+
}
|
|
392
|
+
return { content, response }
|
|
393
|
+
} finally {
|
|
394
|
+
clearTimeout(timeoutTimer)
|
|
395
|
+
combined?.removeEventListener('abort', cancel)
|
|
396
|
+
if (this.activePrompts.get(id) === active) {
|
|
397
|
+
this.activePrompts.delete(id)
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
async cancelSession(sessionId) {
|
|
403
|
+
await this.notify(acp.methods.agent.session.cancel, {
|
|
404
|
+
sessionId: String(sessionId),
|
|
405
|
+
})
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
async setSessionConfigOption(sessionId, configId, value) {
|
|
409
|
+
return this.request(
|
|
410
|
+
acp.methods.agent.session.setConfigOption,
|
|
411
|
+
{
|
|
412
|
+
sessionId: String(sessionId),
|
|
413
|
+
configId: String(configId),
|
|
414
|
+
value: String(value),
|
|
415
|
+
},
|
|
416
|
+
{ timeoutMs: 15_000 },
|
|
417
|
+
)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
async closeSession(sessionId) {
|
|
421
|
+
await this.start()
|
|
422
|
+
if (!this.capabilities.sessionCapabilities?.close) {
|
|
423
|
+
await this.cancelSession(sessionId)
|
|
424
|
+
return
|
|
425
|
+
}
|
|
426
|
+
await this.request(
|
|
427
|
+
acp.methods.agent.session.close,
|
|
428
|
+
{ sessionId: String(sessionId) },
|
|
429
|
+
{ timeoutMs: 5000 },
|
|
430
|
+
)
|
|
431
|
+
this.sessions.delete(String(sessionId))
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
async close() {
|
|
435
|
+
for (const sessionId of this.activePrompts.keys()) {
|
|
436
|
+
this.cancelSession(sessionId).catch(() => {})
|
|
437
|
+
}
|
|
438
|
+
const connection = this.connection
|
|
439
|
+
const child = this.child
|
|
440
|
+
this.connection = null
|
|
441
|
+
this.context = null
|
|
442
|
+
this.initializeResult = null
|
|
443
|
+
connection?.close()
|
|
444
|
+
if (child && child.exitCode == null) child.kill('SIGTERM')
|
|
445
|
+
this.child = null
|
|
446
|
+
}
|
|
447
|
+
}
|