dsh-subagent-agy 0.0.0-stage → 0.2.1
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.
- package/README.md +401 -3
- package/cordis.patch.yml +15 -0
- package/icon.svg +1 -0
- package/lib/classify.js +40 -0
- package/lib/client.js +397 -0
- package/lib/gemini-web.js +400 -0
- package/lib/index.js +183 -0
- package/lib/parallel.js +226 -0
- package/lib/run.js +314 -0
- package/lib/types/index.d.ts +71 -0
- package/lib/wire.js +178 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +81 -6
- package/scripts/gemini_research/browser.py +35 -0
- package/scripts/gemini_research/init_login.py +91 -0
- package/scripts/gemini_research/run_research.py +312 -0
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gemini 网页 Deep Research 的主机侧桥接。
|
|
3
|
+
*
|
|
4
|
+
* 浏览器面板只通过 `/api/dsh-gemini-research/*` 与这里通信:真正的 Chrome
|
|
5
|
+
* 由 Python Playwright 脚本启动,任务严格串行(同一个用户目录只能有一个
|
|
6
|
+
* Chrome 实例)。本模块不接触浏览器会话,只负责排队、超时、日志和结果读取。
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-subagent-agy/gemini-web
|
|
9
|
+
*/
|
|
10
|
+
import { spawn } from 'node:child_process';
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
12
|
+
import { randomUUID } from 'node:crypto';
|
|
13
|
+
import { dirname, join } from 'node:path';
|
|
14
|
+
|
|
15
|
+
/** HTTP 桥接前缀。 */
|
|
16
|
+
export const API_PREFIX = '/api/dsh-gemini-research';
|
|
17
|
+
const PREFIX = 'dsh-gemini-research';
|
|
18
|
+
const MAX_BODY_BYTES = 64 * 1024;
|
|
19
|
+
const MAX_TOPIC_CHARS = 8000;
|
|
20
|
+
|
|
21
|
+
/** 校验并归一化调研主题。 */
|
|
22
|
+
export function validateTopic(value) {
|
|
23
|
+
if (typeof value !== 'string') throw new Error('topic 必须是字符串');
|
|
24
|
+
const topic = value.trim();
|
|
25
|
+
if (topic.length === 0) throw new Error('topic 不能为空');
|
|
26
|
+
if (topic.length > MAX_TOPIC_CHARS) throw new Error(`topic 不能超过 ${MAX_TOPIC_CHARS} 个字符`);
|
|
27
|
+
return topic;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 组装传给 Python 解释器的脚本参数(不含解释器本身)。 */
|
|
31
|
+
export function buildRunArgs({ scriptDir, profileDir, topic, outFile, headless = true, timeoutSec = 900 }) {
|
|
32
|
+
return [
|
|
33
|
+
join(scriptDir, 'run_research.py'),
|
|
34
|
+
'--topic',
|
|
35
|
+
topic,
|
|
36
|
+
'--out',
|
|
37
|
+
outFile,
|
|
38
|
+
'--profile',
|
|
39
|
+
profileDir,
|
|
40
|
+
'--timeout',
|
|
41
|
+
String(timeoutSec),
|
|
42
|
+
...(headless ? ['--headless'] : []),
|
|
43
|
+
];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 只暴露给浏览器的任务摘要(不含完整报告,避免每次轮询传大文本)。 */
|
|
47
|
+
export function summarizeJob(job) {
|
|
48
|
+
if (!job) return null;
|
|
49
|
+
return {
|
|
50
|
+
id: job.id,
|
|
51
|
+
status: job.status,
|
|
52
|
+
topic: job.topic,
|
|
53
|
+
createdAt: job.createdAt,
|
|
54
|
+
startedAt: job.startedAt,
|
|
55
|
+
endedAt: job.endedAt,
|
|
56
|
+
error: job.error,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** 杀掉 Python 及其子进程(Windows 上 Chrome 是孙进程,必须按进程树杀)。 */
|
|
61
|
+
function killTree(child) {
|
|
62
|
+
try {
|
|
63
|
+
if (process.platform === 'win32' && child.pid) {
|
|
64
|
+
spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
child.kill('SIGKILL');
|
|
68
|
+
} catch {}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 把 Python 脚本的错误码/错误文本翻成用户能处理的提示。 */
|
|
72
|
+
export function scriptErrorMessage(code, error) {
|
|
73
|
+
if (error === 'login_required' || code === 2) {
|
|
74
|
+
return '尚未完成 Gemini 登录,请先在面板点「初始化登录」并登录 Google 账号';
|
|
75
|
+
}
|
|
76
|
+
if (error === 'timeout waiting for report') return '等待 Gemini 生成报告超时;可在 profile 目录查看 debug 截图';
|
|
77
|
+
if (error === 'empty report') return 'Gemini 没有返回可提取的报告内容';
|
|
78
|
+
return typeof error === 'string' && error.length > 0 ? error : `调研脚本退出码 ${code}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function readJsonBody(req) {
|
|
82
|
+
return new Promise((resolve, reject) => {
|
|
83
|
+
const chunks = [];
|
|
84
|
+
let size = 0;
|
|
85
|
+
req.on('data', (chunk) => {
|
|
86
|
+
size += chunk.length;
|
|
87
|
+
if (size > MAX_BODY_BYTES) {
|
|
88
|
+
reject(new Error('请求体过大'));
|
|
89
|
+
req.destroy();
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
chunks.push(chunk);
|
|
93
|
+
});
|
|
94
|
+
req.on('end', () => {
|
|
95
|
+
const raw = Buffer.concat(chunks).toString('utf8').trim();
|
|
96
|
+
if (raw.length === 0) {
|
|
97
|
+
resolve({});
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
resolve(JSON.parse(raw));
|
|
102
|
+
} catch {
|
|
103
|
+
reject(new Error('请求体不是合法 JSON'));
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
req.on('error', reject);
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function writeJson(res, status, payload) {
|
|
111
|
+
const body = JSON.stringify(payload);
|
|
112
|
+
res.statusCode = status;
|
|
113
|
+
res.setHeader('content-type', 'application/json; charset=utf-8');
|
|
114
|
+
res.setHeader('cache-control', 'no-store');
|
|
115
|
+
res.end(body);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function route(path, methods, handler) {
|
|
119
|
+
return {
|
|
120
|
+
kind: 'exact',
|
|
121
|
+
path,
|
|
122
|
+
handler: async (req, res) => {
|
|
123
|
+
const method = String(req.method ?? 'GET').toUpperCase();
|
|
124
|
+
if (!methods.includes(method)) {
|
|
125
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: `只接受 ${methods.join('/')}` });
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
try {
|
|
129
|
+
const body = method === 'POST' ? await readJsonBody(req) : {};
|
|
130
|
+
writeJson(res, 200, await handler(body, req));
|
|
131
|
+
} catch (error) {
|
|
132
|
+
const statusCode = typeof error?.statusCode === 'number' ? error.statusCode : 400;
|
|
133
|
+
writeJson(res, statusCode, {
|
|
134
|
+
ok: false,
|
|
135
|
+
code: typeof error?.code === 'string' ? error.code : statusCode === 404 ? 'not-found' : 'bad-request',
|
|
136
|
+
message: error instanceof Error ? error.message : String(error),
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** 简单单任务队列:同一时间只启动一个 runner。 */
|
|
144
|
+
export function createJobQueue({ runner, now = () => Date.now(), idFactory = randomUUID }) {
|
|
145
|
+
const jobs = new Map();
|
|
146
|
+
const pending = [];
|
|
147
|
+
let active = null;
|
|
148
|
+
let lastId = null;
|
|
149
|
+
let pumping = false;
|
|
150
|
+
|
|
151
|
+
function runNext() {
|
|
152
|
+
if (pumping || active !== null) return;
|
|
153
|
+
const next = pending.shift();
|
|
154
|
+
if (next === undefined) return;
|
|
155
|
+
pumping = true;
|
|
156
|
+
active = next;
|
|
157
|
+
next.status = 'running';
|
|
158
|
+
next.startedAt = new Date(now()).toISOString();
|
|
159
|
+
Promise.resolve()
|
|
160
|
+
.then(() => runner(next))
|
|
161
|
+
.then((result) => {
|
|
162
|
+
next.status = 'done';
|
|
163
|
+
next.result = typeof result === 'string' ? result : result && typeof result.report === 'string' ? result.report : String(result ?? '');
|
|
164
|
+
})
|
|
165
|
+
.catch((error) => {
|
|
166
|
+
next.status = 'error';
|
|
167
|
+
next.error = error instanceof Error ? error.message : String(error);
|
|
168
|
+
})
|
|
169
|
+
.finally(() => {
|
|
170
|
+
next.endedAt = new Date(now()).toISOString();
|
|
171
|
+
const waiters = next.waiters;
|
|
172
|
+
next.waiters = [];
|
|
173
|
+
for (const resolve of waiters) resolve(next);
|
|
174
|
+
active = null;
|
|
175
|
+
pumping = false;
|
|
176
|
+
runNext();
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function enqueue(topic) {
|
|
181
|
+
const job = {
|
|
182
|
+
id: idFactory(),
|
|
183
|
+
status: 'queued',
|
|
184
|
+
topic,
|
|
185
|
+
createdAt: new Date(now()).toISOString(),
|
|
186
|
+
startedAt: null,
|
|
187
|
+
endedAt: null,
|
|
188
|
+
result: undefined,
|
|
189
|
+
error: undefined,
|
|
190
|
+
logTail: '',
|
|
191
|
+
waiters: [],
|
|
192
|
+
};
|
|
193
|
+
jobs.set(job.id, job);
|
|
194
|
+
pending.push(job);
|
|
195
|
+
lastId = job.id;
|
|
196
|
+
runNext();
|
|
197
|
+
return job;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
return {
|
|
201
|
+
enqueue,
|
|
202
|
+
get(id) {
|
|
203
|
+
return jobs.get(id) ?? null;
|
|
204
|
+
},
|
|
205
|
+
latest() {
|
|
206
|
+
return lastId === null ? null : jobs.get(lastId) ?? null;
|
|
207
|
+
},
|
|
208
|
+
isRunning() {
|
|
209
|
+
return active !== null;
|
|
210
|
+
},
|
|
211
|
+
pendingCount() {
|
|
212
|
+
return pending.length;
|
|
213
|
+
},
|
|
214
|
+
waitFor(id) {
|
|
215
|
+
const job = jobs.get(id);
|
|
216
|
+
if (job === undefined) return Promise.reject(new Error('找不到该任务'));
|
|
217
|
+
if (job.status === 'done' || job.status === 'error') return Promise.resolve(job);
|
|
218
|
+
return new Promise((resolve) => {
|
|
219
|
+
job.waiters.push(resolve);
|
|
220
|
+
});
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* 注册 Gemini 网页调研的 HTTP 桥接。
|
|
227
|
+
* @param {object} ctx cordis context(需要 webServer 可选注入)。
|
|
228
|
+
* @param {{profileDir: string, python: string, headless: boolean, timeoutMs: number, scriptDir: string}} options
|
|
229
|
+
*/
|
|
230
|
+
export function setupGeminiWeb(ctx, options) {
|
|
231
|
+
if (!ctx || typeof ctx.inject !== 'function') return;
|
|
232
|
+
const runtimeDir = dirname(options.profileDir);
|
|
233
|
+
const jobsDir = join(runtimeDir, 'jobs');
|
|
234
|
+
mkdirSync(jobsDir, { recursive: true });
|
|
235
|
+
|
|
236
|
+
const queue = createJobQueue({
|
|
237
|
+
runner: async (job) => runOneJob(job, options, jobsDir),
|
|
238
|
+
});
|
|
239
|
+
let loginChild = null;
|
|
240
|
+
let loginLog = '';
|
|
241
|
+
|
|
242
|
+
function appendLog(target, chunk) {
|
|
243
|
+
const text = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
|
|
244
|
+
target.logTail = (target.logTail + text).slice(-12000);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function runOneJob(job, opts, dir) {
|
|
248
|
+
const outFile = join(dir, `${job.id}.json`);
|
|
249
|
+
const args = buildRunArgs({
|
|
250
|
+
scriptDir: opts.scriptDir,
|
|
251
|
+
profileDir: opts.profileDir,
|
|
252
|
+
topic: job.topic,
|
|
253
|
+
outFile,
|
|
254
|
+
headless: opts.headless,
|
|
255
|
+
timeoutSec: Math.max(60, Math.round(opts.timeoutMs / 1000)),
|
|
256
|
+
});
|
|
257
|
+
return await new Promise((resolve, reject) => {
|
|
258
|
+
let settled = false;
|
|
259
|
+
const finish = (fn) => {
|
|
260
|
+
if (settled) return;
|
|
261
|
+
settled = true;
|
|
262
|
+
fn();
|
|
263
|
+
};
|
|
264
|
+
let child;
|
|
265
|
+
try {
|
|
266
|
+
child = spawn(opts.python, args, {
|
|
267
|
+
cwd: opts.scriptDir,
|
|
268
|
+
windowsHide: true,
|
|
269
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
270
|
+
});
|
|
271
|
+
} catch (error) {
|
|
272
|
+
reject(new Error(`无法启动 Python:${error instanceof Error ? error.message : String(error)}`));
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
job.child = child;
|
|
276
|
+
const timer = setTimeout(() => {
|
|
277
|
+
killTree(child);
|
|
278
|
+
finish(() => reject(new Error(`调研任务超时(${Math.round(opts.timeoutMs / 1000)}s)`)));
|
|
279
|
+
}, opts.timeoutMs);
|
|
280
|
+
child.stdout?.on('data', (chunk) => appendLog(job, chunk));
|
|
281
|
+
child.stderr?.on('data', (chunk) => appendLog(job, chunk));
|
|
282
|
+
child.on('error', (error) => {
|
|
283
|
+
clearTimeout(timer);
|
|
284
|
+
finish(() => reject(new Error(`Python 启动失败:${error.message}`)));
|
|
285
|
+
});
|
|
286
|
+
child.on('close', (code) => {
|
|
287
|
+
clearTimeout(timer);
|
|
288
|
+
job.exitCode = code;
|
|
289
|
+
let payload;
|
|
290
|
+
try {
|
|
291
|
+
payload = JSON.parse(readFileSync(outFile, 'utf8'));
|
|
292
|
+
} catch {}
|
|
293
|
+
if (payload !== undefined) {
|
|
294
|
+
if (payload.ok === true && typeof payload.report === 'string') {
|
|
295
|
+
finish(() => resolve(payload.report));
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
finish(() => reject(new Error(scriptErrorMessage(code, payload.error || payload.message))));
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
if (code === 2) {
|
|
302
|
+
finish(() => reject(new Error('尚未完成 Gemini 登录,请先在面板点「初始化登录」并登录 Google 账号')));
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
if (code !== 0) {
|
|
306
|
+
finish(() => reject(new Error(`调研脚本退出码 ${code}${job.logTail ? `:${job.logTail.slice(-600)}` : ''}`)));
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
finish(() => reject(new Error('调研脚本没有返回报告')));
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
ctx.inject(['webServer'], (sctx) => {
|
|
315
|
+
sctx.effect(() => {
|
|
316
|
+
const routes = [
|
|
317
|
+
route(API_PREFIX + '/status', ['GET'], async () => ({
|
|
318
|
+
ok: true,
|
|
319
|
+
profileDir: options.profileDir,
|
|
320
|
+
profileExists: existsSync(options.profileDir),
|
|
321
|
+
loginReady: existsSync(join(options.profileDir, 'login-ok.json')),
|
|
322
|
+
python: options.python,
|
|
323
|
+
loginRunning: loginChild !== null,
|
|
324
|
+
running: queue.isRunning(),
|
|
325
|
+
busy: loginChild !== null || queue.isRunning(),
|
|
326
|
+
job: summarizeJob(queue.latest()),
|
|
327
|
+
})),
|
|
328
|
+
route(API_PREFIX + '/login/init', ['POST'], async () => {
|
|
329
|
+
if (loginChild !== null) return { ok: true, alreadyRunning: true };
|
|
330
|
+
if (queue.isRunning()) throw new Error('调研任务进行中,请等结束后再初始化登录');
|
|
331
|
+
loginLog = '';
|
|
332
|
+
const args = [join(options.scriptDir, 'init_login.py'), '--profile', options.profileDir];
|
|
333
|
+
const child = spawn(options.python, args, {
|
|
334
|
+
cwd: options.scriptDir,
|
|
335
|
+
windowsHide: true,
|
|
336
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
337
|
+
});
|
|
338
|
+
loginChild = child;
|
|
339
|
+
child.stdout?.on('data', (chunk) => { loginLog = (loginLog + chunk.toString('utf8')).slice(-8000); });
|
|
340
|
+
child.stderr?.on('data', (chunk) => { loginLog = (loginLog + chunk.toString('utf8')).slice(-8000); });
|
|
341
|
+
child.on('close', () => { loginChild = null; });
|
|
342
|
+
child.on('error', () => { loginChild = null; });
|
|
343
|
+
return { ok: true, started: true };
|
|
344
|
+
}),
|
|
345
|
+
route(API_PREFIX + '/run', ['POST'], async (body) => {
|
|
346
|
+
if (loginChild !== null) throw new Error('正在初始化登录,请等登录窗口关闭后再开始调研');
|
|
347
|
+
const topic = validateTopic(body.topic);
|
|
348
|
+
const job = queue.enqueue(topic);
|
|
349
|
+
return { ok: true, jobId: job.id };
|
|
350
|
+
}),
|
|
351
|
+
route(API_PREFIX + '/job', ['GET'], async (body, req) => {
|
|
352
|
+
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
353
|
+
const id = url.searchParams.get('id') ?? '';
|
|
354
|
+
const job = queue.get(id);
|
|
355
|
+
if (job === null) {
|
|
356
|
+
const error = new Error('找不到该任务');
|
|
357
|
+
error.statusCode = 404;
|
|
358
|
+
error.code = 'not-found';
|
|
359
|
+
throw error;
|
|
360
|
+
}
|
|
361
|
+
return { ok: true, job: { ...summarizeJob(job), result: job.result, logTail: job.logTail } };
|
|
362
|
+
}),
|
|
363
|
+
route(API_PREFIX + '/latest', ['GET'], async () => ({ ok: true, job: summarizeJob(queue.latest()) })),
|
|
364
|
+
];
|
|
365
|
+
const disposers = routes.map((entry) => sctx.webServer.register(entry));
|
|
366
|
+
return () => {
|
|
367
|
+
for (const dispose of disposers) dispose();
|
|
368
|
+
};
|
|
369
|
+
}, `${PREFIX}: bridge`);
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
// 对话内的模型可见工具:与面板共用同一个单任务队列,直接等待报告返回。
|
|
373
|
+
ctx.inject(['tools'], (tctx) => {
|
|
374
|
+
tctx.effect(() => tctx.tools.register({
|
|
375
|
+
name: 'gemini_web_research',
|
|
376
|
+
description: 'Run a Gemini web Deep Research report through the locally logged-in Google AI Pro browser profile. Use this when the user explicitly asks for Gemini Deep Research or a deep multi-source research report. It takes about 5-10 minutes and returns the full report text. The user must first complete the one-time Gemini login in the sidebar "Gemini 调研" panel.',
|
|
377
|
+
parameters: {
|
|
378
|
+
topic: {
|
|
379
|
+
type: 'string',
|
|
380
|
+
description: 'The research topic, including goals, boundaries, and any formatting requirements.',
|
|
381
|
+
},
|
|
382
|
+
},
|
|
383
|
+
output: {
|
|
384
|
+
schema: { type: 'string' },
|
|
385
|
+
render: (_args, value) => [{ type: 'text', text: String(value) }],
|
|
386
|
+
},
|
|
387
|
+
async execute(args) {
|
|
388
|
+
if (!existsSync(join(options.profileDir, 'login-ok.json'))) {
|
|
389
|
+
throw new Error('Gemini 网页调研尚未登录:请先在侧边栏「Gemini 调研」点「初始化登录」并完成 Google 登录');
|
|
390
|
+
}
|
|
391
|
+
if (loginChild !== null) throw new Error('正在初始化 Gemini 登录,请等登录窗口关闭后再试');
|
|
392
|
+
const topic = validateTopic(args?.topic);
|
|
393
|
+
const job = queue.enqueue(topic);
|
|
394
|
+
const finished = await queue.waitFor(job.id);
|
|
395
|
+
if (finished.status === 'error') throw new Error(finished.error || 'Gemini Deep Research 失败');
|
|
396
|
+
return finished.result || '(Gemini 没有返回报告内容)';
|
|
397
|
+
},
|
|
398
|
+
}), `${PREFIX}: tool`);
|
|
399
|
+
});
|
|
400
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Profile-named Antigravity one-shot subagent provider.
|
|
3
|
+
*
|
|
4
|
+
* Every accepted run starts a fresh `agy --print --output-format stream-json`
|
|
5
|
+
* in the delegating Session's workspace and publishes only after the CLI is
|
|
6
|
+
* controllable. Antigravity has no follow-up channel, so the run is external:
|
|
7
|
+
* one execution, no continuation.
|
|
8
|
+
*
|
|
9
|
+
* @module dsh-subagent-agy
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync } from 'node:fs';
|
|
12
|
+
import { join } from 'node:path';
|
|
13
|
+
import { homedir } from 'node:os';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout';
|
|
16
|
+
import { NO_START_CAPABILITIES, assertPositiveFinite, assertUsableCwd } from '@deepseek-ai/dsh-subagent';
|
|
17
|
+
import z from '@deepseek-ai/schemastery';
|
|
18
|
+
import { DEFAULT_ANTIGRAVITY_PERMISSION_MODE, DEFAULT_DISPOSE_GRACE_MS, ANTIGRAVITY_PERMISSION_MODES, startAntigravityRun, startAntigravityRunWithRetry, stripAnsi } from './run.js';
|
|
19
|
+
import { setupGeminiWeb } from './gemini-web.js';
|
|
20
|
+
import { setupParallelTool } from './parallel.js';
|
|
21
|
+
|
|
22
|
+
export const name = 'subagent-antigravity';
|
|
23
|
+
export const inject = ['subagents', 'subprocess'];
|
|
24
|
+
|
|
25
|
+
const PREFIX = 'subagent-antigravity';
|
|
26
|
+
const DEFAULT_PROVIDER_NAME = 'antigravity';
|
|
27
|
+
const DEFAULT_TEAM_PROVIDER_NAME = 'antigravity-team';
|
|
28
|
+
const DEFAULT_PARALLEL_TOOL_NAME = 'subagent_agy_parallel';
|
|
29
|
+
const DEFAULT_MAX_PARALLEL_TASKS = 8;
|
|
30
|
+
const DEFAULT_EXECUTABLE = join(homedir(), '.gemini', 'bin', 'agy.exe');
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Directive used by the `antigravity-team` provider. `/teamwork` itself is an
|
|
34
|
+
* interactive TUI command (it starts a scoping interview), so headless runs use
|
|
35
|
+
* agy's underlying `invoke_subagent` tool instead: one call per independent
|
|
36
|
+
* subtask in the same turn, which agy executes concurrently.
|
|
37
|
+
*/
|
|
38
|
+
export const NATIVE_TEAM_DIRECTIVE = [
|
|
39
|
+
'You are in Antigravity parallel-team mode.',
|
|
40
|
+
'When the task contains two or more independent subtasks, use the `invoke_subagent` tool to launch them concurrently in the same assistant turn.',
|
|
41
|
+
'Call `invoke_subagent` once per subtask with `TypeName` set to `self` for implementation or general work, or `research` for read-only exploration, a short 2-5 word `Role`, and a fully self-contained `Prompt`.',
|
|
42
|
+
'Use at most 4 subagents unless the user explicitly asks for a larger team.',
|
|
43
|
+
'After they finish, integrate their results and cite which subagent produced what.',
|
|
44
|
+
'If a subagent call fails, report the failure; never fabricate its result. If the task is not decomposable, complete it directly.',
|
|
45
|
+
].join('\n');
|
|
46
|
+
|
|
47
|
+
export const Config = z.object({
|
|
48
|
+
providerName: z.string().min(1).default(DEFAULT_PROVIDER_NAME),
|
|
49
|
+
executable: z.string().min(1).default(DEFAULT_EXECUTABLE),
|
|
50
|
+
model: z.string().min(1),
|
|
51
|
+
effort: z.union([...['low', 'medium', 'high', 'xhigh', 'max']]),
|
|
52
|
+
env: z.dict(z.string()).default({}),
|
|
53
|
+
permissionMode: z.union([...ANTIGRAVITY_PERMISSION_MODES]).default(DEFAULT_ANTIGRAVITY_PERMISSION_MODE),
|
|
54
|
+
extraArgs: z.array(z.string()).default([]),
|
|
55
|
+
printTimeout: z.string().min(1),
|
|
56
|
+
jsonSchema: z.string().min(1),
|
|
57
|
+
addDirs: z.array(z.string()),
|
|
58
|
+
fallbackModel: z.string().min(1),
|
|
59
|
+
retryOnRateLimit: z.boolean().default(false),
|
|
60
|
+
disposeGraceMs: z.number().default(DEFAULT_DISPOSE_GRACE_MS),
|
|
61
|
+
geminiProfileDir: z.string().min(1),
|
|
62
|
+
geminiPython: z.string().min(1).default('python'),
|
|
63
|
+
geminiHeadless: z.boolean().default(true),
|
|
64
|
+
geminiTimeoutMs: z.number().default(900000),
|
|
65
|
+
teamProviderName: z.string().min(1).default(DEFAULT_TEAM_PROVIDER_NAME),
|
|
66
|
+
teamEnabled: z.boolean().default(true),
|
|
67
|
+
parallelToolName: z.string().min(1).default(DEFAULT_PARALLEL_TOOL_NAME),
|
|
68
|
+
parallelMaxTasks: z.number().min(1).max(DEFAULT_MAX_PARALLEL_TASKS).default(DEFAULT_MAX_PARALLEL_TASKS),
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
/** Inherited traces that would hijack the child into the delegating CLI session. */
|
|
72
|
+
const SCRUBBED_ENV = Object.freeze(['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'GEMINI_CLI', 'ANTIGRAVITY_SESSION_ID']);
|
|
73
|
+
|
|
74
|
+
class AntigravityProvider {
|
|
75
|
+
capabilities = NO_START_CAPABILITIES;
|
|
76
|
+
inheritsParentContext = false;
|
|
77
|
+
|
|
78
|
+
constructor(name, ctx, config) {
|
|
79
|
+
this.name = name;
|
|
80
|
+
this.ctx = ctx;
|
|
81
|
+
this.config = config;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
start(request) {
|
|
85
|
+
let cwd;
|
|
86
|
+
try {
|
|
87
|
+
cwd = assertUsableCwd(PREFIX, 'child cwd', request.cwd);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (request.signal.aborted) throw new Error(`${PREFIX}: request was aborted before CLI startup`);
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
if (!existsSync(this.config.executable)) throw new Error(`${PREFIX}: Antigravity CLI not found at "${this.config.executable}"; install Antigravity or set the executable option`);
|
|
93
|
+
const env = {};
|
|
94
|
+
for (const key of SCRUBBED_ENV) env[key] = '';
|
|
95
|
+
const spec = {
|
|
96
|
+
cwd,
|
|
97
|
+
executable: this.config.executable,
|
|
98
|
+
...this.config.model === undefined ? {} : { model: this.config.model },
|
|
99
|
+
...this.config.effort === undefined ? {} : { effort: this.config.effort },
|
|
100
|
+
permissionMode: this.config.permissionMode,
|
|
101
|
+
extraArgs: this.config.extraArgs,
|
|
102
|
+
...this.config.promptPrefix === undefined ? {} : { promptPrefix: this.config.promptPrefix },
|
|
103
|
+
...this.config.printTimeout === undefined ? {} : { printTimeout: this.config.printTimeout },
|
|
104
|
+
...this.config.jsonSchema === undefined ? {} : { jsonSchema: this.config.jsonSchema },
|
|
105
|
+
...this.config.addDirs === undefined ? {} : { addDirs: this.config.addDirs },
|
|
106
|
+
...this.config.fallbackModel === undefined ? {} : { fallbackModel: this.config.fallbackModel },
|
|
107
|
+
retryOnRateLimit: this.config.retryOnRateLimit,
|
|
108
|
+
env: { ...env, ...this.config.env },
|
|
109
|
+
disposeGraceMs: this.config.disposeGraceMs,
|
|
110
|
+
spawn: (spawnSpec) => this.ctx.subprocess.spawn(spawnSpec),
|
|
111
|
+
writeStderr: (bytes) => {
|
|
112
|
+
try {
|
|
113
|
+
const text = Buffer.isBuffer(bytes) ? bytes.toString('utf8') : String(bytes);
|
|
114
|
+
process.stderr.write(stripAnsi(text));
|
|
115
|
+
} catch {}
|
|
116
|
+
},
|
|
117
|
+
onError: (error, stopReason) => {
|
|
118
|
+
this.ctx.logger.warn(`${PREFIX} "${this.name}": child run failed (${stopReason}): ${error.message}`);
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
return this.config.fallbackModel === undefined && this.config.retryOnRateLimit !== true
|
|
122
|
+
? startAntigravityRun(request, spec)
|
|
123
|
+
: startAntigravityRunWithRetry(request, spec);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Register one Profile-named Antigravity provider.
|
|
129
|
+
* @param {object} ctx context carrying shared subagent and subprocess services.
|
|
130
|
+
* @param {object} config registry name, CLI path, model, effort, permission mode, and disposal grace.
|
|
131
|
+
*/
|
|
132
|
+
export function apply(ctx, config) {
|
|
133
|
+
const resolved = {
|
|
134
|
+
providerName: config.providerName ?? DEFAULT_PROVIDER_NAME,
|
|
135
|
+
executable: config.executable ?? DEFAULT_EXECUTABLE,
|
|
136
|
+
...config.model === undefined ? {} : { model: config.model },
|
|
137
|
+
...config.effort === undefined ? {} : { effort: config.effort },
|
|
138
|
+
env: config.env ?? {},
|
|
139
|
+
permissionMode: config.permissionMode ?? DEFAULT_ANTIGRAVITY_PERMISSION_MODE,
|
|
140
|
+
extraArgs: config.extraArgs ?? [],
|
|
141
|
+
...config.printTimeout === undefined ? {} : { printTimeout: config.printTimeout },
|
|
142
|
+
...config.jsonSchema === undefined ? {} : { jsonSchema: config.jsonSchema },
|
|
143
|
+
...config.addDirs === undefined ? {} : { addDirs: config.addDirs },
|
|
144
|
+
...config.fallbackModel === undefined ? {} : { fallbackModel: config.fallbackModel },
|
|
145
|
+
retryOnRateLimit: config.retryOnRateLimit ?? false,
|
|
146
|
+
disposeGraceMs: config.disposeGraceMs ?? DEFAULT_DISPOSE_GRACE_MS,
|
|
147
|
+
geminiProfileDir: config.geminiProfileDir ?? join(homedir(), '.dsh', 'gemini-web-research', 'chrome-profile'),
|
|
148
|
+
geminiPython: config.geminiPython ?? 'python',
|
|
149
|
+
geminiHeadless: config.geminiHeadless ?? true,
|
|
150
|
+
geminiTimeoutMs: config.geminiTimeoutMs ?? 900000,
|
|
151
|
+
teamProviderName: config.teamProviderName ?? DEFAULT_TEAM_PROVIDER_NAME,
|
|
152
|
+
teamEnabled: config.teamEnabled ?? true,
|
|
153
|
+
parallelToolName: config.parallelToolName ?? DEFAULT_PARALLEL_TOOL_NAME,
|
|
154
|
+
parallelMaxTasks: config.parallelMaxTasks ?? DEFAULT_MAX_PARALLEL_TASKS,
|
|
155
|
+
};
|
|
156
|
+
assertPositiveFinite(PREFIX, 'disposeGraceMs', resolved.disposeGraceMs);
|
|
157
|
+
if (resolved.disposeGraceMs > MAX_TIMER_DELAY_MS) throw new Error(`${PREFIX}: disposeGraceMs must be no greater than ${MAX_TIMER_DELAY_MS}`);
|
|
158
|
+
ctx.subagents.registerProvider(new AntigravityProvider(resolved.providerName, ctx, resolved));
|
|
159
|
+
if (resolved.teamEnabled) {
|
|
160
|
+
if (resolved.teamProviderName === resolved.providerName) throw new Error(`${PREFIX}: teamProviderName must differ from providerName`);
|
|
161
|
+
ctx.subagents.registerProvider(new AntigravityProvider(resolved.teamProviderName, ctx, { ...resolved, promptPrefix: NATIVE_TEAM_DIRECTIVE }));
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
setupParallelTool(ctx, {
|
|
165
|
+
provider: resolved.providerName,
|
|
166
|
+
toolName: resolved.parallelToolName,
|
|
167
|
+
maxTasks: resolved.parallelMaxTasks,
|
|
168
|
+
});
|
|
169
|
+
} catch (error) {
|
|
170
|
+
ctx.logger?.warn(`${PREFIX}: 并发子智能体工具未启用:${error instanceof Error ? error.message : String(error)}`);
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
setupGeminiWeb(ctx, {
|
|
174
|
+
profileDir: resolved.geminiProfileDir,
|
|
175
|
+
python: resolved.geminiPython,
|
|
176
|
+
headless: resolved.geminiHeadless,
|
|
177
|
+
timeoutMs: resolved.geminiTimeoutMs,
|
|
178
|
+
scriptDir: fileURLToPath(new URL('../scripts/gemini_research', import.meta.url)),
|
|
179
|
+
});
|
|
180
|
+
} catch (error) {
|
|
181
|
+
ctx.logger?.warn(`${PREFIX}: Gemini 网页调研面板未启用:${error instanceof Error ? error.message : String(error)}`);
|
|
182
|
+
}
|
|
183
|
+
}
|