import * as plugins from './plugins.js'; import { ControllerMcpClient, ControllerMcpClientError } from './classes.mcpclient.js'; import { defaultControllerPort } from './classes.config.js'; /** The installed AGL client owns controller discovery and polls one operation without resubmission. */ export const runAuthSwitchCli = async (args: string[]): Promise => { let raw: string | undefined; let port = Number(process.env.AGL_CONTROLLER_PORT || defaultControllerPort); for (let index = 0; index < args.length; index++) { const flag = args[index]; const value = args[++index]; if (flag === '--request' && raw === undefined && value && value.length <= 8192) raw = value; else if (flag === '--port' && value) port = Number(value); else throw new Error('Usage: agl authswitch --request [--port ]'); } if (!raw || !Number.isSafeInteger(port) || port < 1 || port > 65535) throw new Error('Invalid authswitch coordination arguments.'); let request: plugins.authswitch.IAuthSwitchCoordinationRequest; try { const parsed: unknown = JSON.parse(raw); const serviceRequest: unknown = { protocolVersion: 1, action: 'mutate', coordination: parsed }; plugins.authswitch.assertAuthSwitchServiceRequest(serviceRequest); if (serviceRequest.action !== 'mutate') throw new Error(); request = serviceRequest.coordination; } catch { throw new Error('Invalid authswitch coordination request.'); } const client = new ControllerMcpClient({ controllerPort: port }); let operation: plugins.authswitch.IAuthSwitchServiceOperation; try { operation = (await client.authswitch({ protocolVersion: 1, action: 'mutate', coordination: request })).operation; } catch (error) { if (error instanceof ControllerMcpClientError && error.code === 'CONTROLLER_UNAVAILABLE') { process.stdout.write(JSON.stringify({ status: 'unavailable' }) + '\n'); return; } throw error; } const deadline = Date.now() + 340_000; while (operation.state === 'pending') { if (Date.now() > deadline) throw new Error('AGL coordination is still running. Check account and runtime status; do not repeat the mutation.'); await new Promise(resolve => setTimeout(resolve, 500)); operation = (await client.authswitch({ protocolVersion: 1, action: 'get', operationId: operation.id })).operation; } if (operation.state === 'failed' || !operation.result) throw new Error(operation.error ?? 'AGL coordination failed. Check account and runtime status before retrying.'); process.stdout.write(JSON.stringify(operation.result) + '\n'); };