const WebSocket = require('ws')
const IM_TYPE = process.env.AUTCLAW_ADAPTER_IM_TYPE || 'demo'
const controlURL =
process.env.AUTCLAW_ADAPTER_CONNECT_URL ||
`ws://127.0.0.1:${process.env.AUTCLAW_PORT || '8200'}/api/adapters/${IM_TYPE}/connect`
let readySent = false
function text(value) {
return value === undefined || value === null ? '' : String(value).trim()
}
function sendJSON(ws, payload) {
if (!ws || ws.readyState !== WebSocket.OPEN) throw new Error('control websocket is not open')
ws.send(JSON.stringify(payload))
}
function replyWithEcho(ws, message, params, error) {
const response = { aut_echo: text(message && message.aut_echo), ok: !error }
if (error) response.aut_error = text(error.message || error) || 'worker call failed'
else response.aut_params = params && typeof params === 'object' ? params : {}
sendJSON(ws, response)
}
function emitReady(ws) {
if (readySent) return
readySent = true
sendJSON(ws, {
aut_action: 'adapter_worker_ready',
aut_params: {
resolve_account: true,
normalize_inbound: true,
build_outbound: true,
decode_receipt: true,
execute_outbound: false,
emit_inbound_events: false,
request_outbound: false,
},
})
}
function handleWorkerMessage(ws, message) {
const action = text(message && message.aut_action)
if (action === 'adapter_init') {
emitReady(ws)
return
}
if (!text(message && message.aut_echo)) return
Promise.resolve().then(() => {
switch (action) {
case 'adapter_codec_resolve_account':
return replyWithEcho(ws, message, { account_id: '2400000000' })
case 'adapter_codec_normalize_inbound':
return replyWithEcho(ws, message, { events: [] })
case 'adapter_codec_build_outbound':
return replyWithEcho(ws, message, { transport: 'ws', await_receipt: true, raw_payload: {} })
case 'adapter_codec_decode_receipt':
return replyWithEcho(ws, message, { matched: false })
default:
throw new Error(`unsupported action: ${action}`)
}
}).catch((error) => replyWithEcho(ws, message, null, error))
}
function connectControl() {
const ws = new WebSocket(controlURL)
ws.on('message', (data) => handleWorkerMessage(ws, JSON.parse(String(data || '{}'))))
ws.on('close', () => setTimeout(connectControl, 1000))
}
connectControl()