-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
216 lines (192 loc) · 8.77 KB
/
Copy pathserver.js
File metadata and controls
216 lines (192 loc) · 8.77 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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// OpenCode Bridge v5 - wraps opencode-cli as OpenAI-compatible API
// v5: built-in web search agent (CN Bing via curl, free, no API key)
const http = require('http');
const { spawnSync, execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const PORT = process.env.PORT || 4097;
const OPENCODE_CLI = process.env.OPENCODE_CLI || path.join(process.env.LOCALAPPDATA || '', 'OpenCode', 'opencode-cli.exe');
const LOG = path.join(__dirname, 'bridge.log');
function log(msg) {
const line = `[${new Date().toISOString()}] ${msg}`;
console.log(line);
try { fs.appendFileSync(LOG, line + '\n'); } catch(e) {}
}
// ─── Web Search Agent (via system curl → Bing) ───
function webSearch(query, maxResults = 5) {
try {
const q = query.substring(0, 300).replace(/"/g,'');
const url = `https://cn.bing.com/search?q=${encodeURIComponent(q)}&ensearch=0`;
const html = execSync(
`curl.exe -s --max-time 15 -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" -H "Accept-Language: zh-CN,zh;q=0.9" "${url}"`,
{ encoding: 'utf-8', timeout: 16000, maxBuffer: 2*1024*1024, windowsHide: true }
);
const results = [];
const blocks = html.split(/<li[^>]*class="[^"]*b_algo[^"]*"[^>]*>/i).slice(1);
for (const block of blocks) {
if (results.length >= maxResults) break;
const endIdx = block.indexOf('<li');
const part = endIdx > 0 ? block.substring(0, endIdx) : block;
const titleM = /<h2[^>]*><a[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/i.exec(part);
const snippetM = /<p[^>]*class="[^"]*b_lineclamp[^"]*"[^>]*>([\s\S]*?)<\/p>/i.exec(part) ||
/<div[^>]*class="[^"]*b_caption[^"]*"[^>]*>([\s\S]*?)<\/div>/i.exec(part) ||
/<p[^>]*>([\s\S]*?)<\/p>/i.exec(part);
if (titleM) {
const title = titleM[2].replace(/<[^>]*>/g, '').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,"'").trim();
const snippet = snippetM ? snippetM[1].replace(/<[^>]*>/g, '').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,"'").trim() : '';
const link = titleM[1].replace(/&/g,'&');
if (title && !title.includes('下一页') && !title.includes('Next')) {
results.push({ title, snippet, url: link });
}
}
}
log(`SEARCH "${query.substring(0,60)}" → ${results.length} results`);
return Promise.resolve(results);
} catch(e) {
log(`SEARCH_ERR: ${e.message}`);
return Promise.resolve([]);
}
}
// ─── Detect if search is needed ───
function needsSearch(messages) {
const userText = messages
.filter(m => m.role === 'user')
.map(m => typeof m.content === 'string' ? m.content : '')
.join(' ');
// Time-sensitive keywords
const timeRe = /今天|今日|最新|现在|搜索|search|news|trending|当前|实时|刚刚|近期|最新消息|头条|动态|热点/;
// Explicit search request
const explicitRe = /搜索一下|帮我搜|查一下|搜一搜|找一下|look.?up|find info|check (the )?latest/;
return timeRe.test(userText) || explicitRe.test(userText);
}
// ─── Call OpenCode CLI ───
function callCLI(model, prompt) {
log(`CALL model=${model} len=${prompt.length}`);
const r = spawnSync(OPENCODE_CLI, ['run','--format','json','--dangerously-skip-permissions','-m',model,prompt], {
encoding:'utf-8', timeout:180000, maxBuffer:20*1024*1024,
windowsHide:true, env:{...process.env}
});
log(`STDOUT_LEN=${(r.stdout||'').length} STDERR_LEN=${(r.stderr||'').length} EXIT=${r.status} SIG=${r.signal||'none'}`);
if (r.stderr) log(`STDERR: ${r.stderr.trim().substring(0,300)}`);
const lines = (r.stdout||'').trim().split('\n');
let text='', usage={prompt_tokens:0,completion_tokens:0,total_tokens:0};
for (const line of lines) {
if (!line.trim()) continue;
try {
const ev = JSON.parse(line);
if (ev.type==='text' && ev.part?.text) text += ev.part.text;
if (ev.type==='assistant' && ev.part?.text) text += ev.part.text;
if (ev.type==='result' && ev.part?.text) text = ev.part.text;
if (ev.type==='step_finish' && ev.part?.tokens) {
usage = {prompt_tokens:ev.part.tokens.input||0,completion_tokens:ev.part.tokens.output||0,total_tokens:ev.part.tokens.total||0};
}
} catch(e) {
log(`PARSE_ERR: ${e.message}`);
}
}
if (!text && r.error) throw new Error(r.error.message||r.stderr||'unknown');
return {text:text.trim(),usage};
}
// ─── Main call: search if needed, then query CLI ───
async function call(model, messages) {
let searchContext = '';
let searchResults = [];
if (needsSearch(messages)) {
const userText = messages
.filter(m => m.role === 'user')
.map(m => typeof m.content === 'string' ? m.content : '')
.join(' ');
// Extract search query from user text (first 200 chars, or between quotes)
let searchQuery = userText.substring(0, 200);
const quoteMatch = userText.match(/"([^"]{10,200})"/);
if (quoteMatch) searchQuery = quoteMatch[1];
try {
searchResults = await webSearch(searchQuery);
if (searchResults.length > 0) {
searchContext = '\n\n---\n[Web Search Results - for reference only, use this info]\n' +
searchResults.map((r, i) =>
`${i+1}. **${r.title}**\n Link: ${r.url}\n Snippet: ${r.snippet}`
).join('\n\n') +
'\n---\n\nBased on the search results above, now answer: ';
log(`SEARCH_INJECT ${searchResults.length} results, +${searchContext.length} chars`);
}
} catch(e) {
log(`SEARCH_CALL_ERR: ${e.message}`);
}
}
// Build prompt
let prompt = messages.map(m => {
if (m.role === 'system') return `System: ${m.content}`;
if (m.role === 'assistant') return `Assistant: ${m.content}`;
return `User: ${m.content}`;
}).join('\n\n');
if (searchContext) {
prompt += '\n\n' + searchContext;
} else {
prompt += '\n\nAssistant:';
}
const result = callCLI(model, prompt);
result.searchResults = searchResults;
return result;
}
// ─── Server ───
const server = http.createServer((req,res)=>{
res.setHeader('Access-Control-Allow-Origin','*');
res.setHeader('Access-Control-Allow-Methods','POST,GET,OPTIONS');
res.setHeader('Access-Control-Allow-Headers','Content-Type,Authorization');
if (req.method==='OPTIONS') { res.writeHead(204); res.end(); return; }
if (req.method==='GET' && req.url==='/v1/models') {
res.writeHead(200,{'Content-Type':'application/json'});
res.end(JSON.stringify({object:'list',data:[
{id:'opencode/deepseek-v4-flash-free',object:'model',owned_by:'opencode'},
{id:'opencode/mimo-v2.5-free',object:'model',owned_by:'opencode'},
{id:'opencode/nemotron-3-super-free',object:'model',owned_by:'opencode'},
{id:'opencode/big-pickle',object:'model',owned_by:'opencode'},
]})); return;
}
if (req.method==='GET' && req.url==='/health') {
res.writeHead(200,{'Content-Type':'application/json'});
res.end(JSON.stringify({status:'ok'})); return;
}
if (req.method==='POST' && req.url==='/v1/chat/completions') {
let body='';
req.on('data',c=>body+=c);
req.on('end',async ()=>{
try {
const data=JSON.parse(body);
let model=data.model||'opencode/deepseek-v4-flash-free';
if (!model.includes('/')) model = 'opencode/' + model;
const messages=data.messages||[{role:'user',content:'Hello'}];
log(`REQ model=${model} msgs=${messages.length}`);
// Handle content arrays
const msgs = messages.map(m=>{
const c=m.content;
if (Array.isArray(c)) {
const texts=c.filter(p=>p.type==='text').map(p=>p.text).join('\n');
return {...m,content:texts||'(image)'};
}
return m;
});
const result = await call(model, msgs);
const resp = {
id:'chatcmpl-'+Date.now(), object:'chat.completion',
created:Math.floor(Date.now()/1000), model,
choices:[{index:0,message:{role:'assistant',content:result.text},finish_reason:'stop'}],
usage:result.usage,
};
if (result.text.length===0) log('WARN: empty response!');
log(`DONE text=${result.text.length} chars | searched=${result.searchResults.length}`);
res.writeHead(200,{'Content-Type':'application/json'});
res.end(JSON.stringify(resp));
} catch(err) {
log(`ERR ${err.message}`);
res.writeHead(500,{'Content-Type':'application/json'});
res.end(JSON.stringify({error:{message:err.message,type:'server_error'}}));
}
}); return;
}
res.writeHead(404); res.end('Not found');
});
server.listen(PORT,'127.0.0.1',()=>{
log(`Bridge v5 (search agent) on :${PORT}, CLI: ${OPENCODE_CLI}`);
});