-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbroker-proxy.ts
More file actions
147 lines (135 loc) · 4.7 KB
/
Copy pathbroker-proxy.ts
File metadata and controls
147 lines (135 loc) · 4.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/**
* Broker proxy route handlers — forwards requests to the relay broker.
*/
import type { Express, Request, Response } from 'express';
import { createProxyMiddleware, type Options as ProxyOptions } from 'http-proxy-middleware';
import type { RouteContext } from '../lib/types.js';
import { isRecord, parseCommandDescriptor, withWorkflowConventions } from '../lib/utils.js';
export function registerBrokerProxyRoutes(app: Express, ctx: RouteContext): void {
if (!ctx.brokerProxyEnabled || !ctx.relayUrl) {
return;
}
const relayUrl = ctx.relayUrl;
const forwardBrokerJson = async (
req: Request,
res: Response,
endpoint: string,
transformBody?: (body: Record<string, unknown>) => Record<string, unknown>,
) => {
try {
const rawBody = isRecord(req.body) ? { ...req.body } : {};
const body = transformBody ? transformBody(rawBody) : rawBody;
const headers: Record<string, string> = {
'content-type': 'application/json',
};
if (ctx.brokerApiKey) {
headers['x-api-key'] = ctx.brokerApiKey;
}
const workspaceId = req.header('x-workspace-id');
if (workspaceId) {
headers['x-workspace-id'] = workspaceId;
}
const upstream = await fetch(`${relayUrl}${endpoint}`, {
method: req.method,
headers,
body: JSON.stringify(body),
});
const contentType = upstream.headers.get('content-type') ?? '';
const text = await upstream.text();
res.status(upstream.status);
if (contentType) {
res.setHeader('content-type', contentType);
}
if (!text) {
res.end();
return;
}
if (contentType.includes('application/json')) {
try {
res.json(JSON.parse(text));
return;
} catch {
// Fall back to raw text when upstream emits invalid JSON.
}
}
res.send(text);
} catch (err) {
console.error('[dashboard] Broker proxy error:', (err as Error).message);
res.status(502).json({
success: false,
error: 'Broker unavailable',
message: (err as Error).message,
});
}
};
const brokerProxyOptions: ProxyOptions = {
target: relayUrl,
changeOrigin: true,
ws: false,
logger: ctx.verbose ? console : undefined,
on: {
proxyReq: (proxyReq) => {
if (ctx.brokerApiKey) {
proxyReq.setHeader('x-api-key', ctx.brokerApiKey);
}
},
error: (err, _req, res) => {
console.error('[dashboard] Broker proxy error:', (err as Error).message);
if (res && 'writeHead' in res && typeof res.writeHead === 'function') {
res.writeHead(502, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
success: false,
error: 'Broker unavailable',
message: (err as Error).message,
}));
}
},
},
};
app.post('/api/spawn', async (req: Request, res: Response) => {
await forwardBrokerJson(req, res, '/api/spawn', (rawBody) => {
const includeWorkflowConventions =
typeof rawBody.includeWorkflowConventions === 'boolean'
? rawBody.includeWorkflowConventions
: true;
const task = typeof rawBody.task === 'string' ? rawBody.task : undefined;
const parsed = parseCommandDescriptor(
typeof rawBody.cli === 'string' ? rawBody.cli : undefined,
rawBody.args,
typeof rawBody.model === 'string' ? rawBody.model : undefined,
);
const model = parsed.model;
return {
...rawBody,
cli: parsed.cli,
args: parsed.args,
model,
includeWorkflowConventions,
task: withWorkflowConventions(task, includeWorkflowConventions),
};
});
});
app.get('/api/spawned', createProxyMiddleware(brokerProxyOptions));
app.delete('/api/spawned/:name', createProxyMiddleware(brokerProxyOptions));
app.post('/api/spawn/architect', async (req: Request, res: Response) => {
await forwardBrokerJson(req, res, '/api/spawn', (rawBody) => {
const task = typeof rawBody.task === 'string' ? rawBody.task : undefined;
const parsed = parseCommandDescriptor(
typeof rawBody.cli === 'string' ? rawBody.cli : undefined,
rawBody.args,
typeof rawBody.model === 'string' ? rawBody.model : undefined,
);
return {
...rawBody,
name: rawBody.name || 'architect',
cli: parsed.cli,
args: parsed.args,
model: parsed.model,
includeWorkflowConventions: true,
task: withWorkflowConventions(task, true),
};
});
});
// Cloud broker API routes — proxied for cloud workspace features
app.use('/api/brokers', createProxyMiddleware(brokerProxyOptions));
}