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.
Files changed (122) hide show
  1. package/CONTRIBUTING.md +58 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +5 -0
  4. package/PRIVACY.md +34 -0
  5. package/README.md +282 -0
  6. package/README_EN.md +316 -0
  7. package/SECURITY.md +32 -0
  8. package/THIRD_PARTY_NOTICES.md +26 -0
  9. package/cli/bin/qwenaudio.mjs +10 -0
  10. package/cli/package.json +13 -0
  11. package/cli/src/arguments.mjs +247 -0
  12. package/cli/src/gateway-service.mjs +386 -0
  13. package/cli/src/instance-lock.mjs +65 -0
  14. package/cli/src/launcher.mjs +217 -0
  15. package/cli/src/runtime.mjs +356 -0
  16. package/cli/src/webui.mjs +61 -0
  17. package/config/acp/workspace/AGENTS.md +13 -0
  18. package/config/codebuddy/workspace/.codebuddy/models.json +19 -0
  19. package/config/codebuddy/workspace/AGENTS.md +13 -0
  20. package/config/codex/workspace/AGENTS.md +13 -0
  21. package/config/frontend-agent/PROMPT.md +127 -0
  22. package/config/hermes/workspace/AGENTS.md +13 -0
  23. package/config/openclaw/openclaw.json5 +50 -0
  24. package/config/openclaw/workspace/AGENTS.md +9 -0
  25. package/config/opencode/agents/qwen-audio-agent-backend.md +65 -0
  26. package/config/opencode/workspace/AGENTS.md +16 -0
  27. package/config/qoder/workspace/AGENTS.md +16 -0
  28. package/docs/architecture-overview-en.png +0 -0
  29. package/docs/architecture-overview.png +0 -0
  30. package/docs/architecture.md +332 -0
  31. package/docs/configuration.md +386 -0
  32. package/docs/desktop-fluid-orb-thinking.gif +0 -0
  33. package/docs/desktop-goo-orb-thinking.gif +0 -0
  34. package/docs/qwen-audio-agent-three-layer-architecture-en.png +0 -0
  35. package/docs/qwen-audio-agent-three-layer-architecture.png +0 -0
  36. package/package.json +126 -0
  37. package/scripts/audit-dependencies.mjs +109 -0
  38. package/scripts/check-desktop-release-env.mjs +41 -0
  39. package/scripts/codex-acp +58 -0
  40. package/scripts/install-global.mjs +66 -0
  41. package/scripts/openclaw +194 -0
  42. package/scripts/openclaw-gateway +8 -0
  43. package/scripts/opencode-acp +6 -0
  44. package/scripts/opencode-server +179 -0
  45. package/scripts/prepare-build.mjs +38 -0
  46. package/scripts/release-check +182 -0
  47. package/scripts/set-version.mjs +133 -0
  48. package/scripts/start.mjs +43 -0
  49. package/scripts/verify-package.mjs +109 -0
  50. package/server/package.json +18 -0
  51. package/server/src/agent/acp-backend-adapter.mjs +1138 -0
  52. package/server/src/agent/acp-backend-profile.mjs +35 -0
  53. package/server/src/agent/acp-backend-session-utils.mjs +139 -0
  54. package/server/src/agent/acp-process-client.mjs +447 -0
  55. package/server/src/agent/acp-session-registry.mjs +106 -0
  56. package/server/src/agent/acp-session-tools.mjs +257 -0
  57. package/server/src/agent/agent-client.mjs +218 -0
  58. package/server/src/agent/backend-adapter.mjs +15 -0
  59. package/server/src/agent/backend-agent-instructions.mjs +8 -0
  60. package/server/src/agent/backends/codebuddy.mjs +47 -0
  61. package/server/src/agent/backends/codex.mjs +62 -0
  62. package/server/src/agent/backends/generic-acp.mjs +46 -0
  63. package/server/src/agent/backends/hermes.mjs +29 -0
  64. package/server/src/agent/backends/openclaw.mjs +101 -0
  65. package/server/src/agent/backends/opencode.mjs +36 -0
  66. package/server/src/agent/backends/qoder.mjs +47 -0
  67. package/server/src/agent/backends/registry.mjs +32 -0
  68. package/server/src/agent/backends/shared.mjs +46 -0
  69. package/server/src/agent/coordinator.mjs +308 -0
  70. package/server/src/agent/openclaw-adapter.mjs +245 -0
  71. package/server/src/app/bootstrap.mjs +244 -0
  72. package/server/src/conversation/conversation-sync.mjs +183 -0
  73. package/server/src/conversation/frontend-agent-context.mjs +162 -0
  74. package/server/src/conversation/frontend-memory.mjs +328 -0
  75. package/server/src/conversation/profiled-memory-store.mjs +87 -0
  76. package/server/src/conversation/task-result-projector.mjs +18 -0
  77. package/server/src/conversation/user-profile.mjs +234 -0
  78. package/server/src/core/config.mjs +388 -0
  79. package/server/src/core/identity.mjs +93 -0
  80. package/server/src/core/install-paths.mjs +8 -0
  81. package/server/src/core/package-version.mjs +10 -0
  82. package/server/src/core/request-security.mjs +80 -0
  83. package/server/src/index.mjs +67 -0
  84. package/server/src/process/backend-drivers/codebuddy.mjs +15 -0
  85. package/server/src/process/backend-drivers/codex.mjs +15 -0
  86. package/server/src/process/backend-drivers/generic-acp.mjs +18 -0
  87. package/server/src/process/backend-drivers/hermes.mjs +15 -0
  88. package/server/src/process/backend-drivers/openclaw.mjs +35 -0
  89. package/server/src/process/backend-drivers/opencode.mjs +75 -0
  90. package/server/src/process/backend-drivers/qoder.mjs +15 -0
  91. package/server/src/process/backend-drivers/registry.mjs +24 -0
  92. package/server/src/process/backend-drivers/shared.mjs +46 -0
  93. package/server/src/process/managed-backend.mjs +188 -0
  94. package/server/src/task/task-manager.mjs +704 -0
  95. package/server/src/task/task-scheduler.mjs +44 -0
  96. package/server/src/task/task-store.mjs +167 -0
  97. package/server/src/voice/active-voice-clients.mjs +58 -0
  98. package/server/src/voice/announcement/announcement-manager.mjs +402 -0
  99. package/server/src/voice/announcement/announcement-window.mjs +89 -0
  100. package/server/src/voice/input-transcript.mjs +9 -0
  101. package/server/src/voice/realtime-errors.mjs +6 -0
  102. package/server/src/voice/realtime-gateway.mjs +1366 -0
  103. package/server/src/voice/realtime-provider.mjs +771 -0
  104. package/server/src/voice/reconnect-backoff.mjs +30 -0
  105. package/server/src/voice/response-context.mjs +41 -0
  106. package/server/src/voice/session-permission-policy.mjs +56 -0
  107. package/server/src/voice/tools/tool-call-handler.mjs +823 -0
  108. package/server/src/voice/tools/turn-transcripts.mjs +59 -0
  109. package/server/src/voice/turn-correlation.mjs +41 -0
  110. package/shared/backend-catalog.mjs +56 -0
  111. package/shared/gateway-client.mjs +13 -0
  112. package/shared/realtime-events.mjs +55 -0
  113. package/shared/runtime-environment.mjs +422 -0
  114. package/tui/native/macos-voice-io.swift +552 -0
  115. package/tui/native/portaudio-voice-io.py +240 -0
  116. package/tui/package.json +13 -0
  117. package/tui/src/index.mjs +1217 -0
  118. package/tui/src/macos-voice-io.mjs +186 -0
  119. package/tui/src/portaudio-voice-io.mjs +158 -0
  120. package/web/dist/assets/index-BeamDvsE.js +38 -0
  121. package/web/dist/assets/index-BuB0EFih.css +1 -0
  122. package/web/dist/index.html +14 -0
@@ -0,0 +1,552 @@
1
+ import AudioToolbox
2
+ import Foundation
3
+
4
+ private let voiceSampleRate = 48_000.0
5
+
6
+ private struct Command: Decodable {
7
+ let type: String
8
+ let audio: String?
9
+ let sampleRate: Double?
10
+ let enabled: Bool?
11
+ let responseId: String?
12
+ }
13
+
14
+ private func pcmFormat(sampleRate: Double) -> AudioStreamBasicDescription {
15
+ AudioStreamBasicDescription(
16
+ mSampleRate: sampleRate,
17
+ mFormatID: kAudioFormatLinearPCM,
18
+ mFormatFlags: kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked,
19
+ mBytesPerPacket: 2,
20
+ mFramesPerPacket: 1,
21
+ mBytesPerFrame: 2,
22
+ mChannelsPerFrame: 1,
23
+ mBitsPerChannel: 16,
24
+ mReserved: 0
25
+ )
26
+ }
27
+
28
+ private func check(_ status: OSStatus, _ operation: String) throws {
29
+ guard status == noErr else {
30
+ throw NSError(
31
+ domain: "QwenAudioAgentVoiceIO",
32
+ code: Int(status),
33
+ userInfo: [
34
+ NSLocalizedDescriptionKey:
35
+ "\(operation)失败(CoreAudio \(status))",
36
+ ]
37
+ )
38
+ }
39
+ }
40
+
41
+ private func resample(
42
+ _ input: UnsafeBufferPointer<Int16>,
43
+ from sourceRate: Double,
44
+ to targetRate: Double
45
+ ) -> [Int16] {
46
+ guard !input.isEmpty else { return [] }
47
+ if abs(sourceRate - targetRate) < 1 {
48
+ return Array(input)
49
+ }
50
+ let outputCount = max(
51
+ 1,
52
+ Int((Double(input.count) * targetRate / sourceRate).rounded())
53
+ )
54
+ var output = [Int16](repeating: 0, count: outputCount)
55
+ let sourceStep = sourceRate / targetRate
56
+ for index in 0..<outputCount {
57
+ let position = min(Double(input.count - 1), Double(index) * sourceStep)
58
+ let lower = Int(position)
59
+ let upper = min(input.count - 1, lower + 1)
60
+ let fraction = position - Double(lower)
61
+ let value =
62
+ Double(input[lower]) * (1 - fraction)
63
+ + Double(input[upper]) * fraction
64
+ output[index] = Int16(
65
+ max(Double(Int16.min), min(Double(Int16.max), value.rounded()))
66
+ )
67
+ }
68
+ return output
69
+ }
70
+
71
+ private enum PlaybackSignal {
72
+ case started(String)
73
+ case ended(String)
74
+ }
75
+
76
+ private final class PlaybackEntry {
77
+ enum Kind {
78
+ case audio
79
+ case done
80
+ }
81
+
82
+ let kind: Kind
83
+ let responseId: String
84
+ let samples: [Int16]
85
+ var offset = 0
86
+
87
+ init(
88
+ kind: Kind,
89
+ responseId: String,
90
+ samples: [Int16] = []
91
+ ) {
92
+ self.kind = kind
93
+ self.responseId = responseId
94
+ self.samples = samples
95
+ }
96
+ }
97
+
98
+ private final class SampleQueue {
99
+ private let lock = NSLock()
100
+ private var entries: [PlaybackEntry] = []
101
+ private var entryIndex = 0
102
+ private var startedResponses = Set<String>()
103
+
104
+ func append(_ values: [Int16], responseId: String) {
105
+ guard !values.isEmpty else { return }
106
+ lock.lock()
107
+ compactIfNeeded()
108
+ entries.append(PlaybackEntry(
109
+ kind: .audio,
110
+ responseId: responseId,
111
+ samples: values
112
+ ))
113
+ lock.unlock()
114
+ }
115
+
116
+ func finish(responseId: String) {
117
+ guard !responseId.isEmpty else { return }
118
+ lock.lock()
119
+ compactIfNeeded()
120
+ entries.append(PlaybackEntry(
121
+ kind: .done,
122
+ responseId: responseId
123
+ ))
124
+ lock.unlock()
125
+ }
126
+
127
+ func read(
128
+ into destination: UnsafeMutableBufferPointer<Int16>
129
+ ) -> [PlaybackSignal] {
130
+ destination.baseAddress?.initialize(
131
+ repeating: 0,
132
+ count: destination.count
133
+ )
134
+ var signals: [PlaybackSignal] = []
135
+ var consumedResponses = Set<String>()
136
+ var destinationOffset = 0
137
+ lock.lock()
138
+ readLoop: while (
139
+ destinationOffset < destination.count
140
+ && entryIndex < entries.count
141
+ ) {
142
+ let entry = entries[entryIndex]
143
+ switch entry.kind {
144
+ case .done:
145
+ // Wait for the callback after the final samples were handed
146
+ // to CoreAudio before reporting completion.
147
+ if consumedResponses.contains(entry.responseId) {
148
+ break readLoop
149
+ }
150
+ entryIndex += 1
151
+ startedResponses.remove(entry.responseId)
152
+ signals.append(.ended(entry.responseId))
153
+ case .audio:
154
+ if (
155
+ !entry.responseId.isEmpty
156
+ && !startedResponses.contains(entry.responseId)
157
+ ) {
158
+ startedResponses.insert(entry.responseId)
159
+ signals.append(.started(entry.responseId))
160
+ }
161
+ let count = min(
162
+ destination.count - destinationOffset,
163
+ entry.samples.count - entry.offset
164
+ )
165
+ if count > 0 {
166
+ entry.samples.withUnsafeBufferPointer { source in
167
+ destination.baseAddress?.advanced(by: destinationOffset)
168
+ .update(
169
+ from: source.baseAddress!.advanced(
170
+ by: entry.offset
171
+ ),
172
+ count: count
173
+ )
174
+ }
175
+ entry.offset += count
176
+ destinationOffset += count
177
+ if !entry.responseId.isEmpty {
178
+ consumedResponses.insert(entry.responseId)
179
+ }
180
+ }
181
+ if entry.offset >= entry.samples.count {
182
+ entryIndex += 1
183
+ }
184
+ }
185
+ }
186
+ lock.unlock()
187
+ return signals
188
+ }
189
+
190
+ func clear() {
191
+ lock.lock()
192
+ entries.removeAll(keepingCapacity: true)
193
+ entryIndex = 0
194
+ startedResponses.removeAll(keepingCapacity: true)
195
+ lock.unlock()
196
+ }
197
+
198
+ private func compactIfNeeded() {
199
+ if entryIndex > 128, entryIndex * 2 > entries.count {
200
+ entries.removeFirst(entryIndex)
201
+ entryIndex = 0
202
+ }
203
+ }
204
+ }
205
+
206
+ private final class VoiceIO {
207
+ private let outputQueue = DispatchQueue(label: "qwen-audio-agent.voice-io.output")
208
+ private let captureLock = NSLock()
209
+ private let playback = SampleQueue()
210
+ private let captureSampleRate: Double
211
+ private let playbackSampleRate: Double
212
+ private var captureEnabled = true
213
+ private var audioUnit: AudioUnit?
214
+ private var isRunning = false
215
+
216
+ init(captureSampleRate: Double, playbackSampleRate: Double) {
217
+ self.captureSampleRate = captureSampleRate
218
+ self.playbackSampleRate = playbackSampleRate
219
+ }
220
+
221
+ func start() throws {
222
+ var description = AudioComponentDescription(
223
+ componentType: kAudioUnitType_Output,
224
+ componentSubType: kAudioUnitSubType_VoiceProcessingIO,
225
+ componentManufacturer: kAudioUnitManufacturer_Apple,
226
+ componentFlags: 0,
227
+ componentFlagsMask: 0
228
+ )
229
+ guard let component = AudioComponentFindNext(nil, &description) else {
230
+ throw NSError(
231
+ domain: "QwenAudioAgentVoiceIO",
232
+ code: 1,
233
+ userInfo: [NSLocalizedDescriptionKey: "找不到 VoiceProcessingIO"]
234
+ )
235
+ }
236
+
237
+ var unit: AudioUnit?
238
+ try check(
239
+ AudioComponentInstanceNew(component, &unit),
240
+ "创建 VoiceProcessingIO"
241
+ )
242
+ guard let unit else {
243
+ throw NSError(
244
+ domain: "QwenAudioAgentVoiceIO",
245
+ code: 2,
246
+ userInfo: [NSLocalizedDescriptionKey: "VoiceProcessingIO 创建为空"]
247
+ )
248
+ }
249
+ audioUnit = unit
250
+
251
+ var enabled: UInt32 = 1
252
+ try check(
253
+ AudioUnitSetProperty(
254
+ unit,
255
+ kAudioOutputUnitProperty_EnableIO,
256
+ kAudioUnitScope_Input,
257
+ 1,
258
+ &enabled,
259
+ UInt32(MemoryLayout<UInt32>.size)
260
+ ),
261
+ "启用麦克风"
262
+ )
263
+
264
+ // VoiceProcessingIO requires both client sides to share one format.
265
+ // Bus 0 input is the far-end playback reference; bus 1 output is the
266
+ // echo-cancelled microphone signal.
267
+ var format = pcmFormat(sampleRate: voiceSampleRate)
268
+ let formatSize = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
269
+ try check(
270
+ AudioUnitSetProperty(
271
+ unit,
272
+ kAudioUnitProperty_StreamFormat,
273
+ kAudioUnitScope_Input,
274
+ 0,
275
+ &format,
276
+ formatSize
277
+ ),
278
+ "设置播放格式"
279
+ )
280
+ try check(
281
+ AudioUnitSetProperty(
282
+ unit,
283
+ kAudioUnitProperty_StreamFormat,
284
+ kAudioUnitScope_Output,
285
+ 1,
286
+ &format,
287
+ formatSize
288
+ ),
289
+ "设置录音格式"
290
+ )
291
+
292
+ var playbackHandler = AURenderCallbackStruct(
293
+ inputProc: playbackCallback,
294
+ inputProcRefCon: Unmanaged.passUnretained(self).toOpaque()
295
+ )
296
+ try check(
297
+ AudioUnitSetProperty(
298
+ unit,
299
+ kAudioUnitProperty_SetRenderCallback,
300
+ kAudioUnitScope_Input,
301
+ 0,
302
+ &playbackHandler,
303
+ UInt32(MemoryLayout<AURenderCallbackStruct>.size)
304
+ ),
305
+ "设置播放回调"
306
+ )
307
+
308
+ var captureHandler = AURenderCallbackStruct(
309
+ inputProc: captureCallback,
310
+ inputProcRefCon: Unmanaged.passUnretained(self).toOpaque()
311
+ )
312
+ try check(
313
+ AudioUnitSetProperty(
314
+ unit,
315
+ kAudioOutputUnitProperty_SetInputCallback,
316
+ kAudioUnitScope_Global,
317
+ 1,
318
+ &captureHandler,
319
+ UInt32(MemoryLayout<AURenderCallbackStruct>.size)
320
+ ),
321
+ "设置录音回调"
322
+ )
323
+
324
+ try check(AudioUnitInitialize(unit), "初始化 VoiceProcessingIO")
325
+ try check(AudioOutputUnitStart(unit), "启动 VoiceProcessingIO")
326
+ isRunning = true
327
+ emit([
328
+ "type": "ready",
329
+ "aec": true,
330
+ "inputSampleRate": captureSampleRate,
331
+ "voiceProcessingSampleRate": voiceSampleRate,
332
+ ])
333
+ }
334
+
335
+ func setCaptureEnabled(_ enabled: Bool) {
336
+ captureLock.lock()
337
+ captureEnabled = enabled
338
+ captureLock.unlock()
339
+ }
340
+
341
+ private func shouldCapture() -> Bool {
342
+ captureLock.lock()
343
+ defer { captureLock.unlock() }
344
+ return captureEnabled
345
+ }
346
+
347
+ func renderPlayback(
348
+ frameCount: UInt32,
349
+ buffers: UnsafeMutablePointer<AudioBufferList>?
350
+ ) -> OSStatus {
351
+ guard let buffers else { return noErr }
352
+ let list = UnsafeMutableAudioBufferListPointer(buffers)
353
+ for buffer in list {
354
+ guard let data = buffer.mData else { continue }
355
+ let sampleCount = Int(buffer.mDataByteSize) / MemoryLayout<Int16>.size
356
+ let destination = data.bindMemory(to: Int16.self, capacity: sampleCount)
357
+ let signals = playback.read(
358
+ into: UnsafeMutableBufferPointer(
359
+ start: destination,
360
+ count: sampleCount
361
+ )
362
+ )
363
+ for signal in signals {
364
+ switch signal {
365
+ case .started(let responseId):
366
+ emit([
367
+ "type": "playback.started",
368
+ "responseId": responseId,
369
+ ])
370
+ case .ended(let responseId):
371
+ emit([
372
+ "type": "playback.ended",
373
+ "responseId": responseId,
374
+ ])
375
+ }
376
+ }
377
+ }
378
+ return noErr
379
+ }
380
+
381
+ func capture(
382
+ flags: UnsafeMutablePointer<AudioUnitRenderActionFlags>,
383
+ timestamp: UnsafePointer<AudioTimeStamp>,
384
+ frameCount: UInt32
385
+ ) -> OSStatus {
386
+ guard let audioUnit else { return kAudio_ParamError }
387
+ var samples = [Int16](repeating: 0, count: Int(frameCount))
388
+ let status = samples.withUnsafeMutableBytes { bytes -> OSStatus in
389
+ var list = AudioBufferList(
390
+ mNumberBuffers: 1,
391
+ mBuffers: AudioBuffer(
392
+ mNumberChannels: 1,
393
+ mDataByteSize: UInt32(bytes.count),
394
+ mData: bytes.baseAddress
395
+ )
396
+ )
397
+ return AudioUnitRender(
398
+ audioUnit,
399
+ flags,
400
+ timestamp,
401
+ 1,
402
+ frameCount,
403
+ &list
404
+ )
405
+ }
406
+ guard status == noErr, shouldCapture() else { return status }
407
+
408
+ let converted = samples.withUnsafeBufferPointer {
409
+ resample($0, from: voiceSampleRate, to: captureSampleRate)
410
+ }
411
+ let data = converted.withUnsafeBytes { Data($0) }
412
+ emit([
413
+ "type": "audio",
414
+ "audio": data.base64EncodedString(),
415
+ "sampleRate": captureSampleRate,
416
+ ])
417
+ return noErr
418
+ }
419
+
420
+ func play(
421
+ base64: String,
422
+ sampleRate: Double,
423
+ responseId: String
424
+ ) {
425
+ guard
426
+ let data = Data(base64Encoded: base64),
427
+ !data.isEmpty,
428
+ abs(sampleRate - playbackSampleRate) < 1
429
+ else { return }
430
+ let converted = data.withUnsafeBytes { bytes -> [Int16] in
431
+ let input = bytes.bindMemory(to: Int16.self)
432
+ return resample(
433
+ input,
434
+ from: playbackSampleRate,
435
+ to: voiceSampleRate
436
+ )
437
+ }
438
+ playback.append(converted, responseId: responseId)
439
+ }
440
+
441
+ func finishPlayback(responseId: String) {
442
+ playback.finish(responseId: responseId)
443
+ }
444
+
445
+ func clearPlayback() {
446
+ playback.clear()
447
+ }
448
+
449
+ func stop() {
450
+ guard let audioUnit else { return }
451
+ if isRunning {
452
+ AudioOutputUnitStop(audioUnit)
453
+ isRunning = false
454
+ }
455
+ AudioUnitUninitialize(audioUnit)
456
+ AudioComponentInstanceDispose(audioUnit)
457
+ self.audioUnit = nil
458
+ }
459
+
460
+ private func emit(_ payload: [String: Any]) {
461
+ outputQueue.async {
462
+ guard
463
+ let data = try? JSONSerialization.data(withJSONObject: payload),
464
+ var line = String(data: data, encoding: .utf8)
465
+ else { return }
466
+ line.append("\n")
467
+ FileHandle.standardOutput.write(Data(line.utf8))
468
+ }
469
+ }
470
+ }
471
+
472
+ private func playbackCallback(
473
+ _ refCon: UnsafeMutableRawPointer,
474
+ _ flags: UnsafeMutablePointer<AudioUnitRenderActionFlags>,
475
+ _ timestamp: UnsafePointer<AudioTimeStamp>,
476
+ _ bus: UInt32,
477
+ _ frames: UInt32,
478
+ _ data: UnsafeMutablePointer<AudioBufferList>?
479
+ ) -> OSStatus {
480
+ Unmanaged<VoiceIO>.fromOpaque(refCon).takeUnretainedValue()
481
+ .renderPlayback(frameCount: frames, buffers: data)
482
+ }
483
+
484
+ private func captureCallback(
485
+ _ refCon: UnsafeMutableRawPointer,
486
+ _ flags: UnsafeMutablePointer<AudioUnitRenderActionFlags>,
487
+ _ timestamp: UnsafePointer<AudioTimeStamp>,
488
+ _ bus: UInt32,
489
+ _ frames: UInt32,
490
+ _ data: UnsafeMutablePointer<AudioBufferList>?
491
+ ) -> OSStatus {
492
+ Unmanaged<VoiceIO>.fromOpaque(refCon).takeUnretainedValue()
493
+ .capture(flags: flags, timestamp: timestamp, frameCount: frames)
494
+ }
495
+
496
+ private func argument(_ name: String, fallback: Double) -> Double {
497
+ guard
498
+ let index = CommandLine.arguments.firstIndex(of: name),
499
+ CommandLine.arguments.indices.contains(index + 1),
500
+ let value = Double(CommandLine.arguments[index + 1]),
501
+ value > 0
502
+ else { return fallback }
503
+ return value
504
+ }
505
+
506
+ do {
507
+ let voiceIO = VoiceIO(
508
+ captureSampleRate: argument("--capture-rate", fallback: 16_000),
509
+ playbackSampleRate: argument("--playback-rate", fallback: 24_000)
510
+ )
511
+ try voiceIO.start()
512
+ while let line = readLine() {
513
+ guard
514
+ let data = line.data(using: .utf8),
515
+ let command = try? JSONDecoder().decode(Command.self, from: data)
516
+ else { continue }
517
+ switch command.type {
518
+ case "play":
519
+ if let audio = command.audio {
520
+ voiceIO.play(
521
+ base64: audio,
522
+ sampleRate: command.sampleRate ?? 24_000,
523
+ responseId: command.responseId ?? ""
524
+ )
525
+ }
526
+ case "done":
527
+ voiceIO.finishPlayback(responseId: command.responseId ?? "")
528
+ case "clear":
529
+ voiceIO.clearPlayback()
530
+ case "capture":
531
+ voiceIO.setCaptureEnabled(command.enabled != false)
532
+ case "close":
533
+ voiceIO.stop()
534
+ exit(0)
535
+ default:
536
+ continue
537
+ }
538
+ }
539
+ voiceIO.stop()
540
+ } catch {
541
+ let payload: [String: Any] = [
542
+ "type": "error",
543
+ "message": error.localizedDescription,
544
+ ]
545
+ if
546
+ let data = try? JSONSerialization.data(withJSONObject: payload),
547
+ let line = String(data: data, encoding: .utf8)
548
+ {
549
+ FileHandle.standardOutput.write(Data("\(line)\n".utf8))
550
+ }
551
+ exit(1)
552
+ }