dsh-devdock 2.5.0 → 3.0.0
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/CHANGELOG.md +207 -0
- package/README.md +58 -4
- package/cordis.patch.yml +9 -4
- package/index.js +30 -75
- package/package.json +14 -129
- package/CONTRACT.md +0 -639
- package/PUBLISHING.md +0 -175
- package/assets/devdock-256.png +0 -0
- package/assets/devdock-32.png +0 -0
- package/assets/devdock-512.png +0 -0
- package/assets/devdock-64.png +0 -0
- package/assets/icon-256.png +0 -0
- package/assets/screenshots/account-card.png +0 -0
- package/assets/screenshots/cards.png +0 -0
- package/assets/screenshots/manage.png +0 -0
- package/assets/screenshots/push-tab.png +0 -0
- package/assets/screenshots/review.png +0 -0
- package/assets/screenshots/settings.png +0 -0
- package/client.js +0 -12312
- package/src/host/cloudflare.js +0 -1027
- package/src/host/git.js +0 -1664
- package/src/host/github.js +0 -1922
- package/src/host/index.js +0 -4716
- package/src/host/npm.js +0 -424
- package/src/host/npmcli.js +0 -288
- package/src/host/review.js +0 -627
- package/src/host/store.js +0 -1063
package/src/host/index.js
DELETED
|
@@ -1,4716 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* dsh-push — Host half.
|
|
3
|
-
*
|
|
4
|
-
* Owns three things, in this order of importance:
|
|
5
|
-
*
|
|
6
|
-
* 1. THE HTTP API the browser half talks to. Every route in CONTRACT.md §1–§3
|
|
7
|
-
* is registered on the `webServer` service under `/api/push`, with
|
|
8
|
-
* the contract's JSON envelope, CSRF header guard and error-code
|
|
9
|
-
* vocabulary. Route shapes are grouped by PATH and dispatched by METHOD,
|
|
10
|
-
* because the contract puts a read and a write on the same path twice
|
|
11
|
-
* (`/local/commit`, `/releases`) and `webServer.register` refuses two
|
|
12
|
-
* handlers for one (kind, path).
|
|
13
|
-
*
|
|
14
|
-
* 2. THE AGENT TOOL `github_link`, which calls the same service methods so the
|
|
15
|
-
* model and the panel can never disagree about what a push does.
|
|
16
|
-
*
|
|
17
|
-
* 3. THE DURABLE STATE (accounts with their tokens, settings) in one atomic
|
|
18
|
-
* JSON document — see ./store.js.
|
|
19
|
-
*
|
|
20
|
-
* WHY THE ROUTE HANDLERS SNAPSHOT NOTHING BUT RE-READ THE STORE: unlike the
|
|
21
|
-
* reference plugin (which snapshots long-lived services), every input here is
|
|
22
|
-
* per-request user intent — settings, the active account, the repository path.
|
|
23
|
-
* Reading them per request is what makes "switch account" and "change gitPath"
|
|
24
|
-
* take effect on the very next click instead of after a restart. The cordis
|
|
25
|
-
* services this module needs (`webServer`, `tools`) ARE snapshotted at mount,
|
|
26
|
-
* because they only live as long as the owning fiber.
|
|
27
|
-
*
|
|
28
|
-
* @module src/host/index.js
|
|
29
|
-
*/
|
|
30
|
-
|
|
31
|
-
import {
|
|
32
|
-
GithubError,
|
|
33
|
-
// Aliased for the same reason as `repoDetail` below: the service has a
|
|
34
|
-
// `contributions()` method of its own, so an unaliased import inside that
|
|
35
|
-
// method body reads like accidental recursion.
|
|
36
|
-
addCollaborator,
|
|
37
|
-
contributions as fetchContributions,
|
|
38
|
-
createRelease,
|
|
39
|
-
createRepo,
|
|
40
|
-
deleteBranchRemote,
|
|
41
|
-
deleteRelease,
|
|
42
|
-
repoLanguages,
|
|
43
|
-
deleteReleaseAsset,
|
|
44
|
-
uploadReleaseAsset,
|
|
45
|
-
deleteRepo,
|
|
46
|
-
listNotifications,
|
|
47
|
-
listReleases,
|
|
48
|
-
listRepos,
|
|
49
|
-
markNotificationRead,
|
|
50
|
-
pollDeviceFlow,
|
|
51
|
-
protectBranch,
|
|
52
|
-
removeCollaborator,
|
|
53
|
-
// Aliased: the service also has a `repoDetail()` method, and a same-named
|
|
54
|
-
// import inside that method body reads like accidental recursion.
|
|
55
|
-
repoDetail as fetchRepoDetail,
|
|
56
|
-
repoManage as fetchRepoManage,
|
|
57
|
-
renameBranch,
|
|
58
|
-
renameRepo,
|
|
59
|
-
searchRepos,
|
|
60
|
-
startDeviceFlow,
|
|
61
|
-
transferRepo,
|
|
62
|
-
updateRelease,
|
|
63
|
-
updateRepo,
|
|
64
|
-
verifyToken,
|
|
65
|
-
} from './github.js';
|
|
66
|
-
|
|
67
|
-
// 工作区依赖检查需要读本地 package.json。
|
|
68
|
-
import { readFile, writeFile, stat } from 'node:fs/promises';
|
|
69
|
-
import path from 'node:path';
|
|
70
|
-
|
|
71
|
-
// DevDock 的 npm 模块(只读:认账号、列包、看版本)。
|
|
72
|
-
import {
|
|
73
|
-
npmWhoami,
|
|
74
|
-
npmSearchByMaintainer,
|
|
75
|
-
npmPackument,
|
|
76
|
-
npmLatestVersion,
|
|
77
|
-
npmSearchText,
|
|
78
|
-
npmPackageStatus,
|
|
79
|
-
} from './npm.js';
|
|
80
|
-
|
|
81
|
-
// 真正运行 npm(打包 / 发布):文件筛选规则由 npm 自己算,才和用户手动执行一致。
|
|
82
|
-
import { NpmRunner, npmAuthEnv, parsePackJson, mapPackResult } from './npmcli.js';
|
|
83
|
-
import {
|
|
84
|
-
GitError,
|
|
85
|
-
GitRunner,
|
|
86
|
-
githubPushUrl,
|
|
87
|
-
isGithubUrl,
|
|
88
|
-
parseGithubRemote,
|
|
89
|
-
resolveGitBinary,
|
|
90
|
-
} from './git.js';
|
|
91
|
-
import {
|
|
92
|
-
DEFAULT_SETTINGS,
|
|
93
|
-
GithubLinkStore,
|
|
94
|
-
normalizeRepoRoot,
|
|
95
|
-
publicAccount,
|
|
96
|
-
redactSecrets,
|
|
97
|
-
resolveDshHome,
|
|
98
|
-
} from './store.js';
|
|
99
|
-
import {
|
|
100
|
-
BUILTIN_PRESETS,
|
|
101
|
-
REVIEW_CATEGORIES,
|
|
102
|
-
collectReviewChanges,
|
|
103
|
-
normalizeFinding,
|
|
104
|
-
runModelReview,
|
|
105
|
-
scanSecrets,
|
|
106
|
-
MAX_FILE_BYTES,
|
|
107
|
-
sortFindings,
|
|
108
|
-
} from './review.js';
|
|
109
|
-
|
|
110
|
-
// DevDock 的 Cloudflare 模块(REST API v4:账号、Pages、Workers、Zones、部署)。
|
|
111
|
-
import {
|
|
112
|
-
verifyToken as verifyCfToken,
|
|
113
|
-
listAccounts as listCfAccounts,
|
|
114
|
-
listPagesProjects,
|
|
115
|
-
deletePagesProject,
|
|
116
|
-
createPagesProject,
|
|
117
|
-
listWorkers,
|
|
118
|
-
deleteWorker,
|
|
119
|
-
listZones,
|
|
120
|
-
cfOverview,
|
|
121
|
-
detectProjectKind,
|
|
122
|
-
collectUploadFiles,
|
|
123
|
-
createPagesDeployment,
|
|
124
|
-
resolveWorkerMain,
|
|
125
|
-
deployWorkerModule,
|
|
126
|
-
dashUrl,
|
|
127
|
-
} from './cloudflare.js';
|
|
128
|
-
|
|
129
|
-
// Robust Service base class fallback: the same technique the reference plugin
|
|
130
|
-
// uses, so this module can be imported (and exercised) outside a cordis host.
|
|
131
|
-
let ServiceClass;
|
|
132
|
-
try {
|
|
133
|
-
const cordis = await import('@deepseek-ai/cordis');
|
|
134
|
-
ServiceClass = cordis.Service;
|
|
135
|
-
} catch {
|
|
136
|
-
ServiceClass = class Service {
|
|
137
|
-
static init = Symbol.for('cordis.init');
|
|
138
|
-
/**
|
|
139
|
-
* @param {object} ctx
|
|
140
|
-
* @param {string} name
|
|
141
|
-
*/
|
|
142
|
-
constructor(ctx, name) {
|
|
143
|
-
this.ctx = ctx;
|
|
144
|
-
this.name = name;
|
|
145
|
-
}
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/** HTTP prefix shared with the browser half (CONTRACT §0). */
|
|
150
|
-
const ROUTE_PREFIX = '/api/push';
|
|
151
|
-
/** CSRF marker: a custom header forces a CORS preflight the server never answers. */
|
|
152
|
-
const PLUGIN_HEADER = 'x-dsh-plugin';
|
|
153
|
-
const PLUGIN_HEADER_VALUE = 'push';
|
|
154
|
-
|
|
155
|
-
/** Wire code → HTTP status. Statuses are advisory; the code is the contract. */
|
|
156
|
-
const STATUS_BY_CODE = Object.freeze({
|
|
157
|
-
FORBIDDEN: 403,
|
|
158
|
-
BAD_REQUEST: 400,
|
|
159
|
-
NOT_FOUND: 404,
|
|
160
|
-
NO_ACCOUNT: 400,
|
|
161
|
-
UNAUTHORIZED: 401,
|
|
162
|
-
RATE_LIMITED: 429,
|
|
163
|
-
NETWORK: 502,
|
|
164
|
-
GIT_MISSING: 503,
|
|
165
|
-
GIT_FAILED: 400,
|
|
166
|
-
NOT_A_REPO: 400,
|
|
167
|
-
CONFLICT: 409,
|
|
168
|
-
INTERNAL: 500,
|
|
169
|
-
});
|
|
170
|
-
|
|
171
|
-
/* ------------------------------------------------------------------ */
|
|
172
|
-
/* HTTP plumbing */
|
|
173
|
-
/* ------------------------------------------------------------------ */
|
|
174
|
-
|
|
175
|
-
/**
|
|
176
|
-
* An error carrying an HTTP status and a wire code.
|
|
177
|
-
* @param {number} statusCode
|
|
178
|
-
* @param {string} code
|
|
179
|
-
* @param {string} message
|
|
180
|
-
* @returns {Error}
|
|
181
|
-
*/
|
|
182
|
-
function httpError(statusCode, code, message) {
|
|
183
|
-
return Object.assign(new Error(message), { statusCode, code });
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
/**
|
|
187
|
-
* Map any thrown value onto `{status, code, message}`.
|
|
188
|
-
*
|
|
189
|
-
* Both plugin error types already carry a wire code; anything else is an
|
|
190
|
-
* INTERNAL bug, and its message is still scrubbed because an unexpected error
|
|
191
|
-
* may quote a URL with a token in it.
|
|
192
|
-
*
|
|
193
|
-
* @param {unknown} error
|
|
194
|
-
* @param {(text: string) => string} scrub
|
|
195
|
-
* @returns {{status: number, code: string, message: string, githubStatus?: number}}
|
|
196
|
-
*/
|
|
197
|
-
function toWireError(error, scrub) {
|
|
198
|
-
const code = typeof error?.code === 'string' && STATUS_BY_CODE[error.code] !== undefined
|
|
199
|
-
? error.code
|
|
200
|
-
: 'INTERNAL';
|
|
201
|
-
const status = Number.isFinite(error?.statusCode)
|
|
202
|
-
? Number(error.statusCode)
|
|
203
|
-
: (STATUS_BY_CODE[code] ?? 500);
|
|
204
|
-
const message = scrub(String(error?.message ?? error ?? '未知错误'));
|
|
205
|
-
const wire = { status, code, message };
|
|
206
|
-
if (typeof error?.status === 'number') wire.githubStatus = error.status;
|
|
207
|
-
return wire;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
/** Write the contract's success envelope. */
|
|
211
|
-
function sendOk(res, data) {
|
|
212
|
-
sendJson(res, 200, { ok: true, data });
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
/** Write the contract's failure envelope. */
|
|
216
|
-
function sendError(res, wire) {
|
|
217
|
-
const error = { code: wire.code, message: wire.message };
|
|
218
|
-
if (wire.githubStatus !== undefined) error.status = wire.githubStatus;
|
|
219
|
-
sendJson(res, wire.status, { ok: false, error });
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
/** Write JSON with no caching (state must never be served stale). */
|
|
223
|
-
function sendJson(res, status, body) {
|
|
224
|
-
if (res.writableEnded) return;
|
|
225
|
-
res.writeHead(status, {
|
|
226
|
-
'content-type': 'application/json; charset=utf-8',
|
|
227
|
-
'cache-control': 'no-store',
|
|
228
|
-
});
|
|
229
|
-
res.end(JSON.stringify(body));
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
/** Read and parse a JSON object body; `{}` when the body is empty. */
|
|
233
|
-
async function readBody(req) {
|
|
234
|
-
const chunks = [];
|
|
235
|
-
let size = 0;
|
|
236
|
-
for await (const chunk of req) {
|
|
237
|
-
size += chunk.length;
|
|
238
|
-
// 1 MiB is far beyond any legitimate body here (a settings patch); the cap
|
|
239
|
-
// stops an accidental huge upload from being buffered in memory.
|
|
240
|
-
if (size > 1_048_576) throw httpError(413, 'BAD_REQUEST', '请求体过大');
|
|
241
|
-
chunks.push(chunk);
|
|
242
|
-
}
|
|
243
|
-
const text = Buffer.concat(chunks).toString('utf8');
|
|
244
|
-
if (text.trim() === '') return {};
|
|
245
|
-
let data;
|
|
246
|
-
try {
|
|
247
|
-
data = JSON.parse(text);
|
|
248
|
-
} catch {
|
|
249
|
-
throw httpError(400, 'BAD_REQUEST', '请求体不是合法 JSON');
|
|
250
|
-
}
|
|
251
|
-
if (data === null || typeof data !== 'object' || Array.isArray(data)) {
|
|
252
|
-
throw httpError(400, 'BAD_REQUEST', '请求体必须是 JSON 对象');
|
|
253
|
-
}
|
|
254
|
-
return data;
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
/** Query-string accessor bound to one request. */
|
|
258
|
-
function queryOf(req) {
|
|
259
|
-
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
260
|
-
return (name) => url.searchParams.get(name);
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
/* ------------------------------------------------------------------ */
|
|
264
|
-
/* Small validators shared by routes and the agent tool */
|
|
265
|
-
/* ------------------------------------------------------------------ */
|
|
266
|
-
|
|
267
|
-
/** A required non-empty string field, or BAD_REQUEST. */
|
|
268
|
-
function requireString(body, field, label) {
|
|
269
|
-
const value = body?.[field];
|
|
270
|
-
if (typeof value !== 'string' || value.trim() === '') {
|
|
271
|
-
throw httpError(400, 'BAD_REQUEST', `缺少${label ?? field}`);
|
|
272
|
-
}
|
|
273
|
-
return value.trim();
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
/** An optional string field (trimmed), or undefined. */
|
|
277
|
-
function optionalString(value) {
|
|
278
|
-
return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
/** An optional boolean field with a default. */
|
|
282
|
-
function optionalBool(value, fallback) {
|
|
283
|
-
return typeof value === 'boolean' ? value : fallback;
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
/** Clamp an integer query/body value. */
|
|
287
|
-
function clampInt(value, min, max, fallback) {
|
|
288
|
-
const number = Number(value);
|
|
289
|
-
if (!Number.isFinite(number)) return fallback;
|
|
290
|
-
return Math.min(max, Math.max(min, Math.trunc(number)));
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
/**
|
|
294
|
-
* The empty local-status document (`isRepo: false`), in the exact shape of
|
|
295
|
-
* CONTRACT §3 so the client can render an "uninitialised" panel without a
|
|
296
|
-
* second code path.
|
|
297
|
-
* @returns {object}
|
|
298
|
-
*/
|
|
299
|
-
function emptyStatus() {
|
|
300
|
-
return {
|
|
301
|
-
isRepo: false,
|
|
302
|
-
root: null,
|
|
303
|
-
gitDir: null,
|
|
304
|
-
branch: null,
|
|
305
|
-
detachedHead: false,
|
|
306
|
-
upstream: null,
|
|
307
|
-
ahead: 0,
|
|
308
|
-
behind: 0,
|
|
309
|
-
remotes: [],
|
|
310
|
-
githubRemote: null,
|
|
311
|
-
head: null,
|
|
312
|
-
dirty: { changed: 0, staged: 0, untracked: 0, conflicted: 0 },
|
|
313
|
-
files: [],
|
|
314
|
-
tags: [],
|
|
315
|
-
branches: [],
|
|
316
|
-
stashes: [],
|
|
317
|
-
};
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
/* ------------------------------------------------------------------ */
|
|
321
|
-
/* The service */
|
|
322
|
-
/* ------------------------------------------------------------------ */
|
|
323
|
-
|
|
324
|
-
/**
|
|
325
|
-
* The plugin's Host service.
|
|
326
|
-
*
|
|
327
|
-
* Exposed on the context as `githubLink` (a non-injected service, so a second
|
|
328
|
-
* mount can detect itself and no other plugin can be forced to wait on it).
|
|
329
|
-
*/
|
|
330
|
-
/**
|
|
331
|
-
* 判断一个 semver range 是否已经覆盖 latest。
|
|
332
|
-
*
|
|
333
|
-
* 这里故意只做保守判断:能明确判定"已满足"时才返回 true,其余一律当作
|
|
334
|
-
* 可能过时。原因是这个值的用途只是提示「要不要去看看」,误报一次比漏报
|
|
335
|
-
* 一次更容易接受——漏报会让用户以为自己是最新的。
|
|
336
|
-
*
|
|
337
|
-
* @param {string} range package.json 里写的版本范围
|
|
338
|
-
* @param {string} latest 注册表上的最新版本
|
|
339
|
-
* @returns {boolean}
|
|
340
|
-
*/
|
|
341
|
-
function rangeSatisfied(range, latest) {
|
|
342
|
-
const clean = String(range || '').trim();
|
|
343
|
-
if (clean === '' || clean === '*' || clean === 'latest') return true;
|
|
344
|
-
// 精确版本:直接比字符串。
|
|
345
|
-
if (/^v?=\d/.test(clean) || /^\d+\.\d+\.\d+$/.test(clean)) {
|
|
346
|
-
return clean.replace(/^v?=?/, '') === latest;
|
|
347
|
-
}
|
|
348
|
-
// caret / tilde:比较主版本(tilde 再要求次版本相同)。
|
|
349
|
-
const match = clean.match(/^[~^](\d+)(?:\.(\d+))?/);
|
|
350
|
-
if (match) {
|
|
351
|
-
const parts = latest.split('.');
|
|
352
|
-
const major = Number(parts[0]);
|
|
353
|
-
const minor = Number(parts[1]);
|
|
354
|
-
if (!Number.isFinite(major)) return false;
|
|
355
|
-
if (clean.startsWith('^')) return major === Number(match[1]);
|
|
356
|
-
return major === Number(match[1]) && minor === Number(match[2]);
|
|
357
|
-
}
|
|
358
|
-
// 其余写法(>= 、|| 、tag 名等)交给保守分支。
|
|
359
|
-
return false;
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
export class GithubLinkHost extends ServiceClass {
|
|
363
|
-
/**
|
|
364
|
-
* Only `webServer` is REQUIRED. The agent tool is an optional surface, so the
|
|
365
|
-
* tools service is acquired through `ctx.inject(['tools'], ...)` in init():
|
|
366
|
-
* a composition without a tools service still serves the panel, and a
|
|
367
|
-
* composition that adds it later gets the tool without a remount.
|
|
368
|
-
*/
|
|
369
|
-
static inject = ['webServer'];
|
|
370
|
-
|
|
371
|
-
/** @type {GithubLinkStore} durable state. */
|
|
372
|
-
#store;
|
|
373
|
-
/** @type {(disposer: () => void) => void} unwinds routes + tool on unload. */
|
|
374
|
-
#stop = () => {};
|
|
375
|
-
/**
|
|
376
|
-
* A review an agent asked for, waiting for the user to confirm it in the
|
|
377
|
-
* panel. Only one at a time: a second request while this is set is answered
|
|
378
|
-
* with "already pending" instead of stacking dialogs (or looping).
|
|
379
|
-
* @type {{id: string, path: string, presetIds: string[], customPrompt: string,
|
|
380
|
-
* createdAt: number, source: string} | null}
|
|
381
|
-
*/
|
|
382
|
-
#reviewRequest = null;
|
|
383
|
-
|
|
384
|
-
/** Cached `git --version` probe, keyed by the gitPath it was taken for. */
|
|
385
|
-
#gitProbe;
|
|
386
|
-
/** Time of that probe (ms). */
|
|
387
|
-
#gitProbeAt = 0;
|
|
388
|
-
|
|
389
|
-
/**
|
|
390
|
-
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
391
|
-
* @param {{home?: string}} [config] optional overrides (tests).
|
|
392
|
-
*/
|
|
393
|
-
constructor(ctx, config = {}) {
|
|
394
|
-
super(ctx, 'githubLink');
|
|
395
|
-
this.#store = new GithubLinkStore({ home: config.home ?? resolveDshHome() });
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
/** The durable store (also what tests drive directly). */
|
|
399
|
-
get store() {
|
|
400
|
-
return this.#store;
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
/**
|
|
404
|
-
* A runner bound to the CURRENT `gitPath` setting.
|
|
405
|
-
*
|
|
406
|
-
* Constructing one per call is deliberate: it costs nothing, and it means a
|
|
407
|
-
* settings change applies to the next command instead of after a restart.
|
|
408
|
-
* @returns {Promise<GitRunner>}
|
|
409
|
-
*/
|
|
410
|
-
async runner() {
|
|
411
|
-
const settings = await this.#store.settings();
|
|
412
|
-
return new GitRunner({ gitPath: settings.gitPath });
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
/** Every token we hold, for output redaction. */
|
|
416
|
-
async #secrets() {
|
|
417
|
-
return this.#store.secrets();
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
/** Redact known tokens from arbitrary text. */
|
|
421
|
-
async #scrub(text) {
|
|
422
|
-
return redactSecrets(text, await this.#secrets());
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
/**
|
|
426
|
-
* The active account WITH its token, or NO_ACCOUNT.
|
|
427
|
-
* @returns {Promise<object>}
|
|
428
|
-
*/
|
|
429
|
-
async #requireAccount() {
|
|
430
|
-
const account = await this.#store.activeAccount();
|
|
431
|
-
if (!account) {
|
|
432
|
-
throw httpError(400, 'NO_ACCOUNT', '还没有登录 GitHub 账号,请先在设置里添加账号。');
|
|
433
|
-
}
|
|
434
|
-
return account;
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
/**
|
|
438
|
-
* Refresh `lastUsedAt` for an account after it was actually used against
|
|
439
|
-
* GitHub. Failures are swallowed: a bookkeeping write must never fail a
|
|
440
|
-
* successful API call.
|
|
441
|
-
* @param {string} accountId
|
|
442
|
-
*/
|
|
443
|
-
async #touch(accountId) {
|
|
444
|
-
try {
|
|
445
|
-
await this.#store.mutate((state) => {
|
|
446
|
-
const account = state.accounts.find((row) => row.id === accountId);
|
|
447
|
-
if (account) account.lastUsedAt = new Date().toISOString();
|
|
448
|
-
});
|
|
449
|
-
} catch {
|
|
450
|
-
// best effort
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
/**
|
|
455
|
-
* `{available, version}` for the git binary, cached for 10 s.
|
|
456
|
-
*
|
|
457
|
-
* `/state` is polled by the settings page, and each probe spawns a process;
|
|
458
|
-
* a short cache keeps that cheap while still noticing an installed or
|
|
459
|
-
* reconfigured git quickly.
|
|
460
|
-
* @returns {Promise<{available: boolean, version: string|null}>}
|
|
461
|
-
*/
|
|
462
|
-
async gitProbe() {
|
|
463
|
-
const settings = await this.#store.settings();
|
|
464
|
-
const key = settings.gitPath;
|
|
465
|
-
const now = Date.now();
|
|
466
|
-
if (this.#gitProbe && this.#gitProbe.key === key && now - this.#gitProbeAt < 10_000) {
|
|
467
|
-
return this.#gitProbe.value;
|
|
468
|
-
}
|
|
469
|
-
const runner = new GitRunner({ gitPath: key });
|
|
470
|
-
let value;
|
|
471
|
-
try {
|
|
472
|
-
value = await runner.probe();
|
|
473
|
-
} catch {
|
|
474
|
-
value = { available: false, version: null };
|
|
475
|
-
}
|
|
476
|
-
this.#gitProbe = { key, value };
|
|
477
|
-
this.#gitProbeAt = now;
|
|
478
|
-
return value;
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
/* ---------------- CONTRACT §1: accounts + settings ---------------- */
|
|
482
|
-
|
|
483
|
-
/**
|
|
484
|
-
* `GET /state`.
|
|
485
|
-
* @returns {Promise<object>}
|
|
486
|
-
*/
|
|
487
|
-
async state() {
|
|
488
|
-
const [state, probe] = await Promise.all([this.#store.read(), this.gitProbe()]);
|
|
489
|
-
return {
|
|
490
|
-
accounts: state.accounts.map(publicAccount),
|
|
491
|
-
activeAccountId: state.activeAccountId,
|
|
492
|
-
settings: { ...DEFAULT_SETTINGS, ...state.settings },
|
|
493
|
-
gitAvailable: probe.available,
|
|
494
|
-
gitVersion: probe.version,
|
|
495
|
-
};
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
/**
|
|
499
|
-
* `POST /accounts/token` — validate then upsert (same login replaces).
|
|
500
|
-
* @param {{token: string}} body
|
|
501
|
-
* @returns {Promise<{accounts: object[], activeAccountId: string|null}>}
|
|
502
|
-
*/
|
|
503
|
-
async addTokenAccount(body) {
|
|
504
|
-
const token = requireString(body, 'token', ' GitHub 令牌');
|
|
505
|
-
const profile = await verifyToken(token);
|
|
506
|
-
const id = profile.login.toLowerCase();
|
|
507
|
-
const result = await this.#store.mutate((state) => {
|
|
508
|
-
const now = new Date().toISOString();
|
|
509
|
-
const existing = state.accounts.find((account) => account.id === id);
|
|
510
|
-
const record = {
|
|
511
|
-
id,
|
|
512
|
-
login: profile.login,
|
|
513
|
-
name: profile.name,
|
|
514
|
-
avatarUrl: profile.avatarUrl,
|
|
515
|
-
htmlUrl: profile.htmlUrl,
|
|
516
|
-
token,
|
|
517
|
-
tokenKind: 'pat',
|
|
518
|
-
scopes: profile.scopes,
|
|
519
|
-
addedAt: existing?.addedAt ?? now,
|
|
520
|
-
lastUsedAt: now,
|
|
521
|
-
};
|
|
522
|
-
if (existing) state.accounts = state.accounts.map((account) => (account.id === id ? record : account));
|
|
523
|
-
else state.accounts = [...state.accounts, record];
|
|
524
|
-
// Signing in a NEW account makes it active; re-submitting an existing
|
|
525
|
-
// token must not steal the selection from the account the user is using.
|
|
526
|
-
if (!existing || state.activeAccountId === null) state.activeAccountId = id;
|
|
527
|
-
return { accounts: state.accounts.map(publicAccount), activeAccountId: state.activeAccountId };
|
|
528
|
-
});
|
|
529
|
-
return result;
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
/**
|
|
533
|
-
* `POST /accounts/device/start` — begin the OAuth device flow.
|
|
534
|
-
* @returns {Promise<object>}
|
|
535
|
-
*/
|
|
536
|
-
async deviceStart() {
|
|
537
|
-
const settings = await this.#store.settings();
|
|
538
|
-
return startDeviceFlow({ clientId: settings.oauthClientId });
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
/**
|
|
542
|
-
* `POST /accounts/device/poll` — one poll; stores the account on success.
|
|
543
|
-
* @param {{deviceCode: string}} body
|
|
544
|
-
* @returns {Promise<object>}
|
|
545
|
-
*/
|
|
546
|
-
async devicePoll(body) {
|
|
547
|
-
const deviceCode = requireString(body, 'deviceCode', ' deviceCode');
|
|
548
|
-
const settings = await this.#store.settings();
|
|
549
|
-
const polled = await pollDeviceFlow({ clientId: settings.oauthClientId, deviceCode });
|
|
550
|
-
if (polled.status !== 'done' || typeof polled.token !== 'string') return { status: polled.status };
|
|
551
|
-
|
|
552
|
-
// The OAuth token is validated through the same /user call as a PAT, so an
|
|
553
|
-
// account record has identical fields regardless of how it was obtained.
|
|
554
|
-
const profile = await verifyToken(polled.token);
|
|
555
|
-
const id = profile.login.toLowerCase();
|
|
556
|
-
const stored = await this.#store.mutate((state) => {
|
|
557
|
-
const now = new Date().toISOString();
|
|
558
|
-
const existing = state.accounts.find((account) => account.id === id);
|
|
559
|
-
const record = {
|
|
560
|
-
id,
|
|
561
|
-
login: profile.login,
|
|
562
|
-
name: profile.name,
|
|
563
|
-
avatarUrl: profile.avatarUrl,
|
|
564
|
-
htmlUrl: profile.htmlUrl,
|
|
565
|
-
token: polled.token,
|
|
566
|
-
tokenKind: 'oauth',
|
|
567
|
-
scopes: profile.scopes,
|
|
568
|
-
addedAt: existing?.addedAt ?? now,
|
|
569
|
-
lastUsedAt: now,
|
|
570
|
-
};
|
|
571
|
-
if (existing) state.accounts = state.accounts.map((account) => (account.id === id ? record : account));
|
|
572
|
-
else state.accounts = [...state.accounts, record];
|
|
573
|
-
state.activeAccountId = id;
|
|
574
|
-
return { accounts: state.accounts.map(publicAccount), activeAccountId: state.activeAccountId };
|
|
575
|
-
});
|
|
576
|
-
return { status: 'done', ...stored };
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
/**
|
|
580
|
-
* `POST /accounts/activate`.
|
|
581
|
-
* @param {{accountId: string}} body
|
|
582
|
-
* @returns {Promise<{activeAccountId: string}>}
|
|
583
|
-
*/
|
|
584
|
-
async activateAccount(body) {
|
|
585
|
-
const accountId = requireString(body, 'accountId', ' accountId');
|
|
586
|
-
const activeAccountId = await this.#store.mutate((state) => {
|
|
587
|
-
const found = state.accounts.find((account) => account.id === accountId);
|
|
588
|
-
if (!found) throw httpError(404, 'NOT_FOUND', `找不到账号 ${accountId}`);
|
|
589
|
-
state.activeAccountId = accountId;
|
|
590
|
-
return accountId;
|
|
591
|
-
});
|
|
592
|
-
return { activeAccountId };
|
|
593
|
-
}
|
|
594
|
-
|
|
595
|
-
/**
|
|
596
|
-
* `POST /accounts/remove`.
|
|
597
|
-
* @param {{accountId: string}} body
|
|
598
|
-
* @returns {Promise<{accounts: object[], activeAccountId: string|null}>}
|
|
599
|
-
*/
|
|
600
|
-
async removeAccount(body) {
|
|
601
|
-
const accountId = requireString(body, 'accountId', ' accountId');
|
|
602
|
-
return this.#store.mutate((state) => {
|
|
603
|
-
if (!state.accounts.some((account) => account.id === accountId)) {
|
|
604
|
-
throw httpError(404, 'NOT_FOUND', `找不到账号 ${accountId}`);
|
|
605
|
-
}
|
|
606
|
-
state.accounts = state.accounts.filter((account) => account.id !== accountId);
|
|
607
|
-
if (state.activeAccountId === accountId) {
|
|
608
|
-
// Fall back to the first remaining account so the panel is never left
|
|
609
|
-
// showing "active: <deleted>" — or no active account while one exists.
|
|
610
|
-
state.activeAccountId = state.accounts[0]?.id ?? null;
|
|
611
|
-
}
|
|
612
|
-
return { accounts: state.accounts.map(publicAccount), activeAccountId: state.activeAccountId };
|
|
613
|
-
});
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
/**
|
|
617
|
-
* `POST /settings` — merge a validated patch.
|
|
618
|
-
* @param {object} body
|
|
619
|
-
* @returns {Promise<{settings: object}>}
|
|
620
|
-
*/
|
|
621
|
-
async updateSettings(body) {
|
|
622
|
-
const patch = {};
|
|
623
|
-
if (body.oauthClientId !== undefined) {
|
|
624
|
-
if (typeof body.oauthClientId !== 'string') throw httpError(400, 'BAD_REQUEST', 'oauthClientId 必须是字符串');
|
|
625
|
-
patch.oauthClientId = body.oauthClientId.trim();
|
|
626
|
-
}
|
|
627
|
-
if (body.defaultRemote !== undefined) {
|
|
628
|
-
if (typeof body.defaultRemote !== 'string') throw httpError(400, 'BAD_REQUEST', 'defaultRemote 必须是字符串');
|
|
629
|
-
patch.defaultRemote = body.defaultRemote.trim() === '' ? 'origin' : body.defaultRemote.trim();
|
|
630
|
-
}
|
|
631
|
-
if (body.showPrivate !== undefined) {
|
|
632
|
-
if (typeof body.showPrivate !== 'boolean') throw httpError(400, 'BAD_REQUEST', 'showPrivate 必须是布尔值');
|
|
633
|
-
patch.showPrivate = body.showPrivate;
|
|
634
|
-
}
|
|
635
|
-
if (body.gitPath !== undefined) {
|
|
636
|
-
if (typeof body.gitPath !== 'string') throw httpError(400, 'BAD_REQUEST', 'gitPath 必须是字符串');
|
|
637
|
-
patch.gitPath = body.gitPath.trim();
|
|
638
|
-
}
|
|
639
|
-
const settings = await this.#store.updateSettings(patch);
|
|
640
|
-
// A changed gitPath invalidates the cached probe immediately.
|
|
641
|
-
this.#gitProbe = undefined;
|
|
642
|
-
return { settings };
|
|
643
|
-
}
|
|
644
|
-
|
|
645
|
-
/* ---------------- CONTRACT §2: remote repositories ---------------- */
|
|
646
|
-
|
|
647
|
-
/**
|
|
648
|
-
* `GET /repos` — list or search.
|
|
649
|
-
* @param {{page?: string|number, q?: string, affiliation?: string, sort?: string}} query
|
|
650
|
-
* @returns {Promise<object>}
|
|
651
|
-
*/
|
|
652
|
-
async repos(query) {
|
|
653
|
-
const account = await this.#requireAccount();
|
|
654
|
-
const page = clampInt(query.page, 1, 1000, 1);
|
|
655
|
-
const q = optionalString(query.q);
|
|
656
|
-
const result = q
|
|
657
|
-
? await searchRepos({ token: account.token, login: account.login, q, page })
|
|
658
|
-
: await listRepos({
|
|
659
|
-
token: account.token,
|
|
660
|
-
page,
|
|
661
|
-
affiliation: optionalString(query.affiliation),
|
|
662
|
-
sort: optionalString(query.sort),
|
|
663
|
-
});
|
|
664
|
-
await this.#touch(account.id);
|
|
665
|
-
return result;
|
|
666
|
-
}
|
|
667
|
-
|
|
668
|
-
/**
|
|
669
|
-
* `GET /repos/detail`.
|
|
670
|
-
* @param {{owner: string, name: string}} query
|
|
671
|
-
* @returns {Promise<object>}
|
|
672
|
-
*/
|
|
673
|
-
async repoDetail(query) {
|
|
674
|
-
const account = await this.#requireAccount();
|
|
675
|
-
const owner = requireString(query, 'owner', ' owner');
|
|
676
|
-
const name = requireString(query, 'name', ' name');
|
|
677
|
-
const result = await fetchRepoDetail({ token: account.token, owner, name });
|
|
678
|
-
await this.#touch(account.id);
|
|
679
|
-
return result;
|
|
680
|
-
}
|
|
681
|
-
|
|
682
|
-
/**
|
|
683
|
-
* `POST /repos/create`.
|
|
684
|
-
* @param {object} body
|
|
685
|
-
* @returns {Promise<object>}
|
|
686
|
-
*/
|
|
687
|
-
async repoCreate(body) {
|
|
688
|
-
const account = await this.#requireAccount();
|
|
689
|
-
const name = requireString(body, 'name', '仓库名称');
|
|
690
|
-
const result = await createRepo({
|
|
691
|
-
token: account.token,
|
|
692
|
-
name,
|
|
693
|
-
owner: optionalString(body.owner),
|
|
694
|
-
login: account.login,
|
|
695
|
-
private: optionalBool(body.private, true),
|
|
696
|
-
description: optionalString(body.description) ?? '',
|
|
697
|
-
autoInit: optionalBool(body.autoInit, false),
|
|
698
|
-
});
|
|
699
|
-
await this.#touch(account.id);
|
|
700
|
-
return result;
|
|
701
|
-
}
|
|
702
|
-
|
|
703
|
-
/**
|
|
704
|
-
* `POST /repos/delete`.
|
|
705
|
-
* @param {object} body
|
|
706
|
-
* @returns {Promise<{deleted: true}>}
|
|
707
|
-
*/
|
|
708
|
-
async repoDelete(body) {
|
|
709
|
-
const account = await this.#requireAccount();
|
|
710
|
-
const owner = requireString(body, 'owner', ' owner');
|
|
711
|
-
const name = requireString(body, 'name', '仓库名称');
|
|
712
|
-
// Deleting a repository is irreversible and needs the delete_repo
|
|
713
|
-
// scope, so it is gated exactly like rename/transfer: a bare call with no
|
|
714
|
-
// explicit confirmation is a mistake, not an intent.
|
|
715
|
-
if (optionalBool(body.confirm, false) !== true) {
|
|
716
|
-
throw httpError(
|
|
717
|
-
409,
|
|
718
|
-
'CONFLICT',
|
|
719
|
-
`删除仓库会永久移除 ${owner}/${name} 在 GitHub 上的全部代码、Issue、PR 与发布,无法撤销,且需要令牌具备 delete_repo 权限范围。请确认后再执行(confirm: true)。`,
|
|
720
|
-
);
|
|
721
|
-
}
|
|
722
|
-
const result = await deleteRepo({ token: account.token, owner, name });
|
|
723
|
-
await this.#touch(account.id);
|
|
724
|
-
return result;
|
|
725
|
-
}
|
|
726
|
-
|
|
727
|
-
/**
|
|
728
|
-
* `GET /repos/manage` — the management dialog's aggregate (CONTRACT §3c).
|
|
729
|
-
*
|
|
730
|
-
* Partial failure is the NORMAL case here: a token with `repo` but without
|
|
731
|
-
* `admin:repo_hook` still gets stars, branches and releases, and only the
|
|
732
|
-
* webhook field comes back `null` with a Chinese warning. `github.js` does
|
|
733
|
-
* the `Promise.allSettled` fan-out; this method only supplies the account.
|
|
734
|
-
*
|
|
735
|
-
* @param {{owner: string, name: string}} query
|
|
736
|
-
* @returns {Promise<object>}
|
|
737
|
-
*/
|
|
738
|
-
async repoManage(query) {
|
|
739
|
-
const account = await this.#requireAccount();
|
|
740
|
-
const owner = requireString(query, 'owner', ' owner');
|
|
741
|
-
const name = requireString(query, 'name', ' name');
|
|
742
|
-
const result = await fetchRepoManage({ token: account.token, owner, name });
|
|
743
|
-
await this.#touch(account.id);
|
|
744
|
-
return result;
|
|
745
|
-
}
|
|
746
|
-
|
|
747
|
-
/**
|
|
748
|
-
* `POST /repos/update` — edit repository metadata (CONTRACT §3c).
|
|
749
|
-
* @param {object} body
|
|
750
|
-
* @returns {Promise<object>}
|
|
751
|
-
*/
|
|
752
|
-
async repoUpdate(body) {
|
|
753
|
-
const account = await this.#requireAccount();
|
|
754
|
-
const owner = requireString(body, 'owner', ' owner');
|
|
755
|
-
const name = requireString(body, 'name', ' name');
|
|
756
|
-
const patch = {};
|
|
757
|
-
// Every field is optional; only the ones present are forwarded, so the
|
|
758
|
-
// route can no longer wipe a description the user did not edit.
|
|
759
|
-
if (body.description !== undefined) {
|
|
760
|
-
if (typeof body.description !== 'string') throw httpError(400, 'BAD_REQUEST', 'description 必须是字符串');
|
|
761
|
-
patch.description = body.description;
|
|
762
|
-
}
|
|
763
|
-
if (body.homepage !== undefined) {
|
|
764
|
-
if (typeof body.homepage !== 'string') throw httpError(400, 'BAD_REQUEST', 'homepage 必须是字符串');
|
|
765
|
-
patch.homepage = body.homepage;
|
|
766
|
-
}
|
|
767
|
-
if (body.private !== undefined) {
|
|
768
|
-
if (typeof body.private !== 'boolean') throw httpError(400, 'BAD_REQUEST', 'private 必须是布尔值');
|
|
769
|
-
patch.private = body.private;
|
|
770
|
-
}
|
|
771
|
-
if (body.archived !== undefined) {
|
|
772
|
-
if (typeof body.archived !== 'boolean') throw httpError(400, 'BAD_REQUEST', 'archived 必须是布尔值');
|
|
773
|
-
patch.archived = body.archived;
|
|
774
|
-
}
|
|
775
|
-
if (body.topics !== undefined) {
|
|
776
|
-
if (!Array.isArray(body.topics)) throw httpError(400, 'BAD_REQUEST', 'topics 必须是字符串数组');
|
|
777
|
-
patch.topics = body.topics.filter((topic) => typeof topic === 'string');
|
|
778
|
-
}
|
|
779
|
-
if (body.defaultBranch !== undefined) {
|
|
780
|
-
if (typeof body.defaultBranch !== 'string') throw httpError(400, 'BAD_REQUEST', 'defaultBranch 必须是字符串');
|
|
781
|
-
patch.defaultBranch = body.defaultBranch;
|
|
782
|
-
}
|
|
783
|
-
const result = await updateRepo({ token: account.token, owner, name, patch });
|
|
784
|
-
await this.#touch(account.id);
|
|
785
|
-
// A topics-only change issues no PATCH, so there is no repository payload;
|
|
786
|
-
// refetch it so every caller keeps receiving a complete repo object.
|
|
787
|
-
if (!result.repo) {
|
|
788
|
-
const refreshed = await fetchRepoDetail({ token: account.token, owner, name });
|
|
789
|
-
return { repo: refreshed.repo, topics: result.topics };
|
|
790
|
-
}
|
|
791
|
-
return result;
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
/**
|
|
795
|
-
* `POST /repos/branch/rename`.
|
|
796
|
-
* @param {object} body
|
|
797
|
-
* @returns {Promise<object>}
|
|
798
|
-
*/
|
|
799
|
-
async repoBranchRename(body) {
|
|
800
|
-
const account = await this.#requireAccount();
|
|
801
|
-
const owner = requireString(body, 'owner', ' owner');
|
|
802
|
-
const name = requireString(body, 'name', ' name');
|
|
803
|
-
const from = requireString(body, 'from', '原分支名');
|
|
804
|
-
const to = requireString(body, 'to', '新分支名');
|
|
805
|
-
const result = await renameBranch({ token: account.token, owner, name, from, to });
|
|
806
|
-
await this.#touch(account.id);
|
|
807
|
-
return result;
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
/**
|
|
811
|
-
* `POST /repos/branch/delete`.
|
|
812
|
-
* @param {object} body
|
|
813
|
-
* @returns {Promise<object>}
|
|
814
|
-
*/
|
|
815
|
-
async repoBranchDelete(body) {
|
|
816
|
-
const account = await this.#requireAccount();
|
|
817
|
-
const owner = requireString(body, 'owner', ' owner');
|
|
818
|
-
const name = requireString(body, 'name', ' name');
|
|
819
|
-
const branch = requireString(body, 'branch', '分支名');
|
|
820
|
-
const result = await deleteBranchRemote({ token: account.token, owner, name, branch });
|
|
821
|
-
await this.#touch(account.id);
|
|
822
|
-
return result;
|
|
823
|
-
}
|
|
824
|
-
|
|
825
|
-
/**
|
|
826
|
-
* `POST /repos/branch/protect`.
|
|
827
|
-
* @param {object} body
|
|
828
|
-
* @returns {Promise<object>}
|
|
829
|
-
*/
|
|
830
|
-
async repoBranchProtect(body) {
|
|
831
|
-
const account = await this.#requireAccount();
|
|
832
|
-
const owner = requireString(body, 'owner', ' owner');
|
|
833
|
-
const name = requireString(body, 'name', ' name');
|
|
834
|
-
const branch = requireString(body, 'branch', '分支名');
|
|
835
|
-
if (typeof body.protected !== 'boolean') {
|
|
836
|
-
throw httpError(400, 'BAD_REQUEST', 'protected 必须是布尔值');
|
|
837
|
-
}
|
|
838
|
-
const result = await protectBranch({
|
|
839
|
-
token: account.token,
|
|
840
|
-
owner,
|
|
841
|
-
name,
|
|
842
|
-
branch,
|
|
843
|
-
protected: body.protected,
|
|
844
|
-
});
|
|
845
|
-
await this.#touch(account.id);
|
|
846
|
-
return result;
|
|
847
|
-
}
|
|
848
|
-
|
|
849
|
-
/**
|
|
850
|
-
* `POST /repos/release/delete`.
|
|
851
|
-
* @param {object} body
|
|
852
|
-
* @returns {Promise<object>}
|
|
853
|
-
*/
|
|
854
|
-
async repoReleaseDelete(body) {
|
|
855
|
-
const account = await this.#requireAccount();
|
|
856
|
-
const owner = requireString(body, 'owner', ' owner');
|
|
857
|
-
const name = requireString(body, 'name', ' name');
|
|
858
|
-
const id = requireString(body, 'id', ' release id');
|
|
859
|
-
const result = await deleteRelease({ token: account.token, owner, name, id });
|
|
860
|
-
await this.#touch(account.id);
|
|
861
|
-
return result;
|
|
862
|
-
}
|
|
863
|
-
|
|
864
|
-
/**
|
|
865
|
-
* `POST /repos/release/update`.
|
|
866
|
-
* @param {object} body
|
|
867
|
-
* @returns {Promise<object>}
|
|
868
|
-
*/
|
|
869
|
-
async repoReleaseUpdate(body) {
|
|
870
|
-
const account = await this.#requireAccount();
|
|
871
|
-
const owner = requireString(body, 'owner', ' owner');
|
|
872
|
-
const name = requireString(body, 'name', ' name');
|
|
873
|
-
const id = requireString(body, 'id', ' release id');
|
|
874
|
-
const patch = {};
|
|
875
|
-
// `body.name` is the REPOSITORY name (used above), so the release title
|
|
876
|
-
// must arrive under its own key. Accepting `name` here made it
|
|
877
|
-
// impossible to set a title without corrupting the repository path.
|
|
878
|
-
const releaseName = optionalString(body.releaseName) ?? optionalString(body.title);
|
|
879
|
-
if (releaseName !== undefined) {
|
|
880
|
-
patch.name = releaseName;
|
|
881
|
-
}
|
|
882
|
-
if (body.body !== undefined) {
|
|
883
|
-
if (typeof body.body !== 'string') throw httpError(400, 'BAD_REQUEST', 'body 必须是字符串');
|
|
884
|
-
patch.body = body.body;
|
|
885
|
-
}
|
|
886
|
-
if (body.draft !== undefined) {
|
|
887
|
-
if (typeof body.draft !== 'boolean') throw httpError(400, 'BAD_REQUEST', 'draft 必须是布尔值');
|
|
888
|
-
patch.draft = body.draft;
|
|
889
|
-
}
|
|
890
|
-
if (body.prerelease !== undefined) {
|
|
891
|
-
if (typeof body.prerelease !== 'boolean') throw httpError(400, 'BAD_REQUEST', 'prerelease 必须是布尔值');
|
|
892
|
-
patch.prerelease = body.prerelease;
|
|
893
|
-
}
|
|
894
|
-
// Never spread `patch` into an object that already has `name`: the spread
|
|
895
|
-
// overwrote the repository name with the release title.
|
|
896
|
-
const result = await updateRelease({
|
|
897
|
-
token: account.token,
|
|
898
|
-
owner,
|
|
899
|
-
repo: name,
|
|
900
|
-
id,
|
|
901
|
-
title: patch.name,
|
|
902
|
-
body: patch.body,
|
|
903
|
-
draft: patch.draft,
|
|
904
|
-
prerelease: patch.prerelease,
|
|
905
|
-
});
|
|
906
|
-
await this.#touch(account.id);
|
|
907
|
-
return result;
|
|
908
|
-
}
|
|
909
|
-
|
|
910
|
-
/**
|
|
911
|
-
* `POST /repos/collaborator/add`.
|
|
912
|
-
* @param {object} body
|
|
913
|
-
* @returns {Promise<object>}
|
|
914
|
-
*/
|
|
915
|
-
async repoCollaboratorAdd(body) {
|
|
916
|
-
const account = await this.#requireAccount();
|
|
917
|
-
const owner = requireString(body, 'owner', ' owner');
|
|
918
|
-
const name = requireString(body, 'name', ' name');
|
|
919
|
-
const user = requireString(body, 'user', ' GitHub 用户名');
|
|
920
|
-
const permission = optionalString(body.permission) ?? 'push';
|
|
921
|
-
const result = await addCollaborator({ token: account.token, owner, name, user, permission });
|
|
922
|
-
await this.#touch(account.id);
|
|
923
|
-
return result;
|
|
924
|
-
}
|
|
925
|
-
|
|
926
|
-
/**
|
|
927
|
-
* `POST /repos/collaborator/remove`.
|
|
928
|
-
* @param {object} body
|
|
929
|
-
* @returns {Promise<object>}
|
|
930
|
-
*/
|
|
931
|
-
async repoCollaboratorRemove(body) {
|
|
932
|
-
const account = await this.#requireAccount();
|
|
933
|
-
const owner = requireString(body, 'owner', ' owner');
|
|
934
|
-
const name = requireString(body, 'name', ' name');
|
|
935
|
-
const user = requireString(body, 'user', ' GitHub 用户名');
|
|
936
|
-
const result = await removeCollaborator({ token: account.token, owner, name, user });
|
|
937
|
-
await this.#touch(account.id);
|
|
938
|
-
return result;
|
|
939
|
-
}
|
|
940
|
-
|
|
941
|
-
/**
|
|
942
|
-
* `POST /repos/rename` — destructive; requires `confirm: true`.
|
|
943
|
-
*
|
|
944
|
-
* The confirmation pattern (and its wording) is copied from `/local/reset`
|
|
945
|
-
* and `/local/discard-all`: a 409 CONFLICT that says exactly what will
|
|
946
|
-
* happen and what field acknowledges it.
|
|
947
|
-
*
|
|
948
|
-
* @param {object} body
|
|
949
|
-
* @returns {Promise<object>}
|
|
950
|
-
*/
|
|
951
|
-
async repoRename(body) {
|
|
952
|
-
const account = await this.#requireAccount();
|
|
953
|
-
const owner = requireString(body, 'owner', ' owner');
|
|
954
|
-
const name = requireString(body, 'name', ' name');
|
|
955
|
-
const newName = requireString(body, 'newName', '新仓库名称');
|
|
956
|
-
if (optionalBool(body.confirm, false) !== true) {
|
|
957
|
-
throw httpError(
|
|
958
|
-
409,
|
|
959
|
-
'CONFLICT',
|
|
960
|
-
`重命名仓库会改变它的地址:旧链接会被 GitHub 重定向,但本地远端、其他协作者的克隆都需要手动更新。请确认后再执行(confirm: true)。`,
|
|
961
|
-
);
|
|
962
|
-
}
|
|
963
|
-
const result = await renameRepo({ token: account.token, owner, name, newName });
|
|
964
|
-
await this.#touch(account.id);
|
|
965
|
-
return result;
|
|
966
|
-
}
|
|
967
|
-
|
|
968
|
-
/**
|
|
969
|
-
* `POST /repos/transfer` — destructive; requires `confirm: true`.
|
|
970
|
-
* @param {object} body
|
|
971
|
-
* @returns {Promise<object>}
|
|
972
|
-
*/
|
|
973
|
-
async repoTransfer(body) {
|
|
974
|
-
const account = await this.#requireAccount();
|
|
975
|
-
const owner = requireString(body, 'owner', ' owner');
|
|
976
|
-
const name = requireString(body, 'name', ' name');
|
|
977
|
-
const newOwner = requireString(body, 'newOwner', '新的仓库所有者');
|
|
978
|
-
if (optionalBool(body.confirm, false) !== true) {
|
|
979
|
-
throw httpError(
|
|
980
|
-
409,
|
|
981
|
-
'CONFLICT',
|
|
982
|
-
`转移仓库会把它移交给 ${newOwner},原所有者将失去管理权限,且 Webhook、协作者与 Actions 配置可能失效。请确认后再执行(confirm: true)。`,
|
|
983
|
-
);
|
|
984
|
-
}
|
|
985
|
-
const result = await transferRepo({ token: account.token, owner, name, newOwner });
|
|
986
|
-
await this.#touch(account.id);
|
|
987
|
-
return result;
|
|
988
|
-
}
|
|
989
|
-
|
|
990
|
-
/**
|
|
991
|
-
* `GET /releases`.
|
|
992
|
-
* @param {{owner: string, repo: string}} query
|
|
993
|
-
* @returns {Promise<object>}
|
|
994
|
-
*/
|
|
995
|
-
async releases(query) {
|
|
996
|
-
const account = await this.#requireAccount();
|
|
997
|
-
const owner = requireString(query, 'owner', ' owner');
|
|
998
|
-
const repo = requireString(query, 'repo', '仓库名称');
|
|
999
|
-
const result = await listReleases({ token: account.token, owner, repo });
|
|
1000
|
-
await this.#touch(account.id);
|
|
1001
|
-
return result;
|
|
1002
|
-
}
|
|
1003
|
-
|
|
1004
|
-
/**
|
|
1005
|
-
* `POST /releases`.
|
|
1006
|
-
* @param {object} body
|
|
1007
|
-
* @returns {Promise<object>}
|
|
1008
|
-
*/
|
|
1009
|
-
async releaseCreate(body) {
|
|
1010
|
-
const account = await this.#requireAccount();
|
|
1011
|
-
const owner = requireString(body, 'owner', ' owner');
|
|
1012
|
-
const repo = requireString(body, 'repo', '仓库名称');
|
|
1013
|
-
const tagName = requireString(body, 'tagName', '标签名');
|
|
1014
|
-
const result = await createRelease({
|
|
1015
|
-
token: account.token,
|
|
1016
|
-
owner,
|
|
1017
|
-
repo,
|
|
1018
|
-
tagName,
|
|
1019
|
-
name: optionalString(body.name),
|
|
1020
|
-
body: optionalString(body.body),
|
|
1021
|
-
target: optionalString(body.target),
|
|
1022
|
-
draft: optionalBool(body.draft, false),
|
|
1023
|
-
prerelease: optionalBool(body.prerelease, false),
|
|
1024
|
-
});
|
|
1025
|
-
await this.#touch(account.id);
|
|
1026
|
-
return result;
|
|
1027
|
-
}
|
|
1028
|
-
|
|
1029
|
-
/**
|
|
1030
|
-
* `GET /contributions` — the active account's contribution calendar.
|
|
1031
|
-
*
|
|
1032
|
-
* `login` defaults to the ACTIVE account so the panel can ask with no
|
|
1033
|
-
* arguments; naming another user is allowed because GitHub's calendar is
|
|
1034
|
-
* public for public activity. A token without `read:user` resolves to
|
|
1035
|
-
* `{unavailable:true}` rather than an error, so the page keeps rendering.
|
|
1036
|
-
*
|
|
1037
|
-
* @param {{login?: string, days?: string|number}} query
|
|
1038
|
-
* @returns {Promise<object>}
|
|
1039
|
-
*/
|
|
1040
|
-
async contributions(query) {
|
|
1041
|
-
const account = await this.#requireAccount();
|
|
1042
|
-
const login = optionalString(query.login) ?? account.login;
|
|
1043
|
-
const result = await fetchContributions({
|
|
1044
|
-
token: account.token,
|
|
1045
|
-
login,
|
|
1046
|
-
days: clampInt(query.days, 1, 365, 365),
|
|
1047
|
-
});
|
|
1048
|
-
// A scope-denied answer never reached GitHub's data, so it is not "use".
|
|
1049
|
-
if (result.unavailable !== true) await this.#touch(account.id);
|
|
1050
|
-
return result;
|
|
1051
|
-
}
|
|
1052
|
-
|
|
1053
|
-
/**
|
|
1054
|
-
* `GET /notifications` — recent notification threads ("最近消息").
|
|
1055
|
-
* @param {{all?: string, limit?: string|number}} query
|
|
1056
|
-
* @returns {Promise<{items: object[], unreadCount: number}>}
|
|
1057
|
-
*/
|
|
1058
|
-
async notifications(query) {
|
|
1059
|
-
const account = await this.#requireAccount();
|
|
1060
|
-
const result = await listNotifications({
|
|
1061
|
-
token: account.token,
|
|
1062
|
-
// Query strings carry text, so `true`/`1` are the accepted truthy forms;
|
|
1063
|
-
// anything else means "unread only", which is GitHub's own default.
|
|
1064
|
-
all: query.all === 'true' || query.all === '1',
|
|
1065
|
-
limit: clampInt(query.limit, 1, 50, 30),
|
|
1066
|
-
});
|
|
1067
|
-
await this.#touch(account.id);
|
|
1068
|
-
return result;
|
|
1069
|
-
}
|
|
1070
|
-
|
|
1071
|
-
/**
|
|
1072
|
-
* `POST /notifications/read` — mark one thread read.
|
|
1073
|
-
* @param {{id: string}} body
|
|
1074
|
-
* @returns {Promise<{read: true}>}
|
|
1075
|
-
*/
|
|
1076
|
-
async notificationRead(body) {
|
|
1077
|
-
const account = await this.#requireAccount();
|
|
1078
|
-
const id = requireString(body, 'id', '通知 id');
|
|
1079
|
-
const result = await markNotificationRead({ token: account.token, id });
|
|
1080
|
-
await this.#touch(account.id);
|
|
1081
|
-
return result;
|
|
1082
|
-
}
|
|
1083
|
-
|
|
1084
|
-
/* ---------------- CONTRACT §3: local repository ---------------- */
|
|
1085
|
-
|
|
1086
|
-
/**
|
|
1087
|
-
* `GET /local/status`.
|
|
1088
|
-
*
|
|
1089
|
-
* A directory that is not a repository is a NORMAL answer here
|
|
1090
|
-
* (`isRepo:false`), not an error: the sidebar's Git tab is opened on arbitrary
|
|
1091
|
-
* workspaces, most of which are not repositories.
|
|
1092
|
-
* @param {string} path
|
|
1093
|
-
* @returns {Promise<object>}
|
|
1094
|
-
*/
|
|
1095
|
-
async localStatus(path) {
|
|
1096
|
-
const target = requireString({ path }, 'path', '仓库路径');
|
|
1097
|
-
const settings = await this.#store.settings();
|
|
1098
|
-
const runner = new GitRunner({ gitPath: settings.gitPath });
|
|
1099
|
-
const secrets = await this.#secrets();
|
|
1100
|
-
const probe = await runner.probe();
|
|
1101
|
-
if (!probe.available) {
|
|
1102
|
-
throw new GitError(
|
|
1103
|
-
'GIT_MISSING',
|
|
1104
|
-
`找不到可用的 git(当前使用 ${runner.binary})。请安装 Git,或在插件设置里填写「git 路径」。`,
|
|
1105
|
-
);
|
|
1106
|
-
}
|
|
1107
|
-
try {
|
|
1108
|
-
return await runner.status(target, { defaultRemote: settings.defaultRemote, secrets });
|
|
1109
|
-
} catch (error) {
|
|
1110
|
-
// ONLY "not a repository" degrades to the empty document. A bad argument
|
|
1111
|
-
// (a relative path, say) must still be reported: silently answering
|
|
1112
|
-
// "not a repo" would hide the real problem from the panel.
|
|
1113
|
-
if (error?.code === 'NOT_A_REPO') return emptyStatus();
|
|
1114
|
-
throw error;
|
|
1115
|
-
}
|
|
1116
|
-
}
|
|
1117
|
-
|
|
1118
|
-
/**
|
|
1119
|
-
* `GET /local/log`.
|
|
1120
|
-
* @param {{path: string, limit?: string|number, ref?: string}} query
|
|
1121
|
-
* @returns {Promise<object>}
|
|
1122
|
-
*/
|
|
1123
|
-
async localLog(query) {
|
|
1124
|
-
const path = requireString(query, 'path', '仓库路径');
|
|
1125
|
-
const settings = await this.#store.settings();
|
|
1126
|
-
const runner = new GitRunner({ gitPath: settings.gitPath });
|
|
1127
|
-
return runner.log(path, {
|
|
1128
|
-
limit: clampInt(query.limit, 1, 500, 60),
|
|
1129
|
-
ref: optionalString(query.ref),
|
|
1130
|
-
secrets: await this.#secrets(),
|
|
1131
|
-
});
|
|
1132
|
-
}
|
|
1133
|
-
|
|
1134
|
-
/**
|
|
1135
|
-
* `GET /local/diff`.
|
|
1136
|
-
* @param {{path: string, file: string, staged?: string}} query
|
|
1137
|
-
* @returns {Promise<object>}
|
|
1138
|
-
*/
|
|
1139
|
-
async localDiff(query) {
|
|
1140
|
-
const path = requireString(query, 'path', '仓库路径');
|
|
1141
|
-
const file = requireString(query, 'file', '文件路径');
|
|
1142
|
-
const settings = await this.#store.settings();
|
|
1143
|
-
const runner = new GitRunner({ gitPath: settings.gitPath });
|
|
1144
|
-
return runner.diff(path, {
|
|
1145
|
-
file,
|
|
1146
|
-
staged: query.staged === 'true' || query.staged === '1',
|
|
1147
|
-
secrets: await this.#secrets(),
|
|
1148
|
-
});
|
|
1149
|
-
}
|
|
1150
|
-
|
|
1151
|
-
/**
|
|
1152
|
-
* `GET /local/commit`.
|
|
1153
|
-
* @param {{path: string, sha: string}} query
|
|
1154
|
-
* @returns {Promise<object>}
|
|
1155
|
-
*/
|
|
1156
|
-
async localCommitDetail(query) {
|
|
1157
|
-
const path = requireString(query, 'path', '仓库路径');
|
|
1158
|
-
const sha = requireString(query, 'sha', '提交 SHA');
|
|
1159
|
-
const settings = await this.#store.settings();
|
|
1160
|
-
const runner = new GitRunner({ gitPath: settings.gitPath });
|
|
1161
|
-
return runner.commitDetail(path, { sha, secrets: await this.#secrets() });
|
|
1162
|
-
}
|
|
1163
|
-
|
|
1164
|
-
/**
|
|
1165
|
-
* `GET /local/remotes`.
|
|
1166
|
-
* @param {{path: string}} query
|
|
1167
|
-
* @returns {Promise<object>}
|
|
1168
|
-
*/
|
|
1169
|
-
async localRemotes(query) {
|
|
1170
|
-
const path = requireString(query, 'path', '仓库路径');
|
|
1171
|
-
const settings = await this.#store.settings();
|
|
1172
|
-
const runner = new GitRunner({ gitPath: settings.gitPath });
|
|
1173
|
-
return runner.remotes(path, { secrets: await this.#secrets() });
|
|
1174
|
-
}
|
|
1175
|
-
|
|
1176
|
-
/**
|
|
1177
|
-
* The token to attach to one network command, if any.
|
|
1178
|
-
*
|
|
1179
|
-
* A GitHub **https** remote is authenticated with the active account's token;
|
|
1180
|
-
* an ssh remote must NOT get one (git+ssh has its own auth and an injected
|
|
1181
|
-
* header would be meaningless). A missing account on an https GitHub remote
|
|
1182
|
-
* is reported as NO_ACCOUNT rather than letting git fail with a credential
|
|
1183
|
-
* prompt that cannot appear.
|
|
1184
|
-
*
|
|
1185
|
-
* @param {GitRunner} runner
|
|
1186
|
-
* @param {string} path
|
|
1187
|
-
* @param {string} remote
|
|
1188
|
-
* @returns {Promise<string|undefined>}
|
|
1189
|
-
*/
|
|
1190
|
-
async #tokenForRemote(runner, path, remote) {
|
|
1191
|
-
let remotes;
|
|
1192
|
-
try {
|
|
1193
|
-
remotes = (await runner.remotes(path)).remotes;
|
|
1194
|
-
} catch {
|
|
1195
|
-
// A repository whose remotes cannot be read gets no token; git's own
|
|
1196
|
-
// error is clearer than anything invented here.
|
|
1197
|
-
return undefined;
|
|
1198
|
-
}
|
|
1199
|
-
const target = remotes.find((row) => row.name === remote);
|
|
1200
|
-
if (!target || !isGithubUrl(target.url)) return undefined;
|
|
1201
|
-
if (!/^https?:/i.test(target.url)) return undefined;
|
|
1202
|
-
// The remote's URL is quoted (it is not a secret) because it is what tells
|
|
1203
|
-
// the user WHICH remote needs an account.
|
|
1204
|
-
return this.#githubHttpsToken(`远端 ${remote}`, `(${target.url})`);
|
|
1205
|
-
}
|
|
1206
|
-
|
|
1207
|
-
/**
|
|
1208
|
-
* The active account's token, requiring an account to exist.
|
|
1209
|
-
*
|
|
1210
|
-
* Shared by the remote-name path and the by-URL path (CONTRACT §3b): an
|
|
1211
|
-
* anonymous https push to GitHub is pointless — it can only fail with a
|
|
1212
|
-
* credential prompt that this Host deliberately never shows — so both paths
|
|
1213
|
-
* fail early with an actionable NO_ACCOUNT.
|
|
1214
|
-
*
|
|
1215
|
-
* @param {string} what names the destination in the Chinese message.
|
|
1216
|
-
* @param {string} [detail] an extra parenthetical (the URL, already scrubbed
|
|
1217
|
-
* by the caller — real tokens never reach this argument).
|
|
1218
|
-
* @returns {Promise<string>}
|
|
1219
|
-
*/
|
|
1220
|
-
async #githubHttpsToken(what, detail = '') {
|
|
1221
|
-
const account = await this.#store.activeAccount();
|
|
1222
|
-
if (!account) {
|
|
1223
|
-
throw httpError(
|
|
1224
|
-
400,
|
|
1225
|
-
'NO_ACCOUNT',
|
|
1226
|
-
`${what} 指向 GitHub${detail},需要先在设置里登录一个 GitHub 账号才能认证。`,
|
|
1227
|
-
);
|
|
1228
|
-
}
|
|
1229
|
-
return account.token;
|
|
1230
|
-
}
|
|
1231
|
-
|
|
1232
|
-
/** Build a runner from the live settings (shared by every local route). */
|
|
1233
|
-
async #runnerAndSecrets() {
|
|
1234
|
-
const settings = await this.#store.settings();
|
|
1235
|
-
return {
|
|
1236
|
-
settings,
|
|
1237
|
-
runner: new GitRunner({ gitPath: settings.gitPath }),
|
|
1238
|
-
secrets: await this.#secrets(),
|
|
1239
|
-
};
|
|
1240
|
-
}
|
|
1241
|
-
|
|
1242
|
-
/**
|
|
1243
|
-
* The remote a network route should use.
|
|
1244
|
-
*
|
|
1245
|
-
* The body's `remote` wins; otherwise `settings.defaultRemote` — which exists
|
|
1246
|
-
* precisely so a user whose repositories all use `upstream` does not have to
|
|
1247
|
-
* name it on every click — and `origin` only as the last resort.
|
|
1248
|
-
*
|
|
1249
|
-
* @param {string|undefined} requested the body's `remote`.
|
|
1250
|
-
* @param {string} defaultRemote the settings value.
|
|
1251
|
-
* @returns {string}
|
|
1252
|
-
*/
|
|
1253
|
-
#pickRemote(requested, defaultRemote) {
|
|
1254
|
-
const explicit = optionalString(requested);
|
|
1255
|
-
if (explicit !== undefined) return explicit;
|
|
1256
|
-
const fallback = optionalString(defaultRemote);
|
|
1257
|
-
return fallback ?? 'origin';
|
|
1258
|
-
}
|
|
1259
|
-
|
|
1260
|
-
/**
|
|
1261
|
-
* `POST /local/init`.
|
|
1262
|
-
* @param {object} body
|
|
1263
|
-
* @returns {Promise<{output: string}>}
|
|
1264
|
-
*/
|
|
1265
|
-
async localInit(body) {
|
|
1266
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1267
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1268
|
-
const initOut = await runner.init(path, { secrets });
|
|
1269
|
-
let output = initOut.output;
|
|
1270
|
-
if (optionalBool(body.createRemote, false)) {
|
|
1271
|
-
const account = await this.#requireAccount();
|
|
1272
|
-
// The name defaults to the directory's own name, which is what a
|
|
1273
|
-
// "create the GitHub repo for this folder" button means.
|
|
1274
|
-
const name = optionalString(body.name)
|
|
1275
|
-
?? initOut.root.replace(/[\\/]+$/, '').split(/[\\/]/).pop()
|
|
1276
|
-
?? '';
|
|
1277
|
-
if (name === '') throw httpError(400, 'BAD_REQUEST', '缺少仓库名称');
|
|
1278
|
-
const created = await createRepo({
|
|
1279
|
-
token: account.token,
|
|
1280
|
-
name,
|
|
1281
|
-
owner: optionalString(body.owner),
|
|
1282
|
-
login: account.login,
|
|
1283
|
-
private: optionalBool(body.private, true),
|
|
1284
|
-
description: '',
|
|
1285
|
-
autoInit: false,
|
|
1286
|
-
});
|
|
1287
|
-
await this.#touch(account.id);
|
|
1288
|
-
const remoteName = optionalString(body.remoteName) ?? 'origin';
|
|
1289
|
-
const remoteOut = await runner.setRemote(initOut.root, {
|
|
1290
|
-
name: remoteName,
|
|
1291
|
-
url: created.repo.cloneUrl,
|
|
1292
|
-
secrets,
|
|
1293
|
-
});
|
|
1294
|
-
output += remoteOut.output;
|
|
1295
|
-
}
|
|
1296
|
-
// Stage everything but do NOT commit: the first commit message is the
|
|
1297
|
-
// user's decision, and the contract says so explicitly.
|
|
1298
|
-
const staged = await runner.stageAll(initOut.root, { secrets });
|
|
1299
|
-
return { output: output + staged.output };
|
|
1300
|
-
}
|
|
1301
|
-
|
|
1302
|
-
/**
|
|
1303
|
-
* `POST /local/remote`.
|
|
1304
|
-
* @param {object} body
|
|
1305
|
-
* @returns {Promise<{output: string}>}
|
|
1306
|
-
*/
|
|
1307
|
-
async localSetRemote(body) {
|
|
1308
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1309
|
-
const url = requireString(body, 'url', '远端地址');
|
|
1310
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1311
|
-
const name = optionalString(body.name) ?? 'origin';
|
|
1312
|
-
// The contract asks this route to resolve owner/repo for a GitHub URL. The
|
|
1313
|
-
// response may only carry `output`, so the resolution is used for the one
|
|
1314
|
-
// thing it can do here: reject a GitHub URL that names no repository
|
|
1315
|
-
// (`https://github.com/`, `https://github.com/owner`), which git would
|
|
1316
|
-
// otherwise store happily and every later push would fail against.
|
|
1317
|
-
if (isGithubUrl(url) && parseGithubRemote(url) === null) {
|
|
1318
|
-
throw httpError(400, 'BAD_REQUEST', `无法从 ${url} 解析出 GitHub 仓库(需要 owner/repo 两段)。`);
|
|
1319
|
-
}
|
|
1320
|
-
const result = await runner.setRemote(path, { name, url, secrets });
|
|
1321
|
-
return { output: result.output };
|
|
1322
|
-
}
|
|
1323
|
-
|
|
1324
|
-
/**
|
|
1325
|
-
* `POST /local/fetch`.
|
|
1326
|
-
* @param {object} body
|
|
1327
|
-
* @returns {Promise<{output: string}>}
|
|
1328
|
-
*/
|
|
1329
|
-
async localFetch(body) {
|
|
1330
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1331
|
-
const { settings, runner, secrets } = await this.#runnerAndSecrets();
|
|
1332
|
-
const remote = this.#pickRemote(body.remote, settings.defaultRemote);
|
|
1333
|
-
const token = await this.#tokenForRemote(runner, path, remote);
|
|
1334
|
-
const result = await runner.fetch(path, {
|
|
1335
|
-
remote,
|
|
1336
|
-
prune: optionalBool(body.prune, false),
|
|
1337
|
-
token,
|
|
1338
|
-
secrets,
|
|
1339
|
-
});
|
|
1340
|
-
return { output: result.output };
|
|
1341
|
-
}
|
|
1342
|
-
|
|
1343
|
-
/**
|
|
1344
|
-
* `POST /local/pull`.
|
|
1345
|
-
* @param {object} body
|
|
1346
|
-
* @returns {Promise<{output: string}>}
|
|
1347
|
-
*/
|
|
1348
|
-
async localPull(body) {
|
|
1349
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1350
|
-
const { settings, runner, secrets } = await this.#runnerAndSecrets();
|
|
1351
|
-
const remote = this.#pickRemote(body.remote, settings.defaultRemote);
|
|
1352
|
-
const token = await this.#tokenForRemote(runner, path, remote);
|
|
1353
|
-
const result = await runner.pull(path, {
|
|
1354
|
-
remote,
|
|
1355
|
-
branch: optionalString(body.branch),
|
|
1356
|
-
rebase: optionalBool(body.rebase, false),
|
|
1357
|
-
token,
|
|
1358
|
-
secrets,
|
|
1359
|
-
});
|
|
1360
|
-
return { output: result.output };
|
|
1361
|
-
}
|
|
1362
|
-
|
|
1363
|
-
/**
|
|
1364
|
-
* `POST /local/push` — CONTRACT §3b aware.
|
|
1365
|
-
*
|
|
1366
|
-
* DESTINATION RESOLUTION (in order, the first one that applies wins):
|
|
1367
|
-
*
|
|
1368
|
-
* 1. `target: {owner, repo}` — an existing remote that already points at
|
|
1369
|
-
* that repository is REUSED (so `.git/config` is untouched AND the push
|
|
1370
|
-
* gets the remote's own refspec/upstream behaviour); otherwise the push
|
|
1371
|
-
* goes straight to the constructed https URL. The URL form is the
|
|
1372
|
-
* contract's "never pollute the user's .git/config" rule; the token
|
|
1373
|
-
* rides along as a per-invocation header and is never written anywhere.
|
|
1374
|
-
* 2. `remote: '<name>'` — the pre-§3b behaviour, unchanged.
|
|
1375
|
-
* 3. Neither → the remembered target for this branch, then
|
|
1376
|
-
* `settings.defaultRemote`, then `origin`.
|
|
1377
|
-
*
|
|
1378
|
-
* MEMORY: only a SUCCESSFUL push is recorded, and `remember: false` opts out.
|
|
1379
|
-
* The key is `(normalizedRepoRoot, branch)` — see store.js.
|
|
1380
|
-
*
|
|
1381
|
-
* @param {object} body
|
|
1382
|
-
* @returns {Promise<{output: string}>}
|
|
1383
|
-
*/
|
|
1384
|
-
async localPush(body) {
|
|
1385
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1386
|
-
const { settings, runner, secrets } = await this.#runnerAndSecrets();
|
|
1387
|
-
|
|
1388
|
-
// The root is resolved ONCE and reused: `assertRepo` costs three git spawns
|
|
1389
|
-
// and every helper below would otherwise repeat it.
|
|
1390
|
-
const root = (await runner.assertRepo(path, { secrets })).root;
|
|
1391
|
-
// The branch is needed THREE times here (memory lookup, refspec, memory
|
|
1392
|
-
// write), so it is resolved once. An explicit body.branch wins; otherwise
|
|
1393
|
-
// the branch HEAD points at; a detached HEAD leaves it null.
|
|
1394
|
-
const requestedBranch = optionalString(body.branch);
|
|
1395
|
-
const branch = requestedBranch ?? (await runner.currentBranch(path, { secrets, root }));
|
|
1396
|
-
|
|
1397
|
-
const target = await this.#resolvePushTarget({
|
|
1398
|
-
runner,
|
|
1399
|
-
path,
|
|
1400
|
-
root,
|
|
1401
|
-
branch,
|
|
1402
|
-
settings,
|
|
1403
|
-
body,
|
|
1404
|
-
secrets,
|
|
1405
|
-
});
|
|
1406
|
-
|
|
1407
|
-
// A URL push has no configured merge ref, so it NEEDS an explicit refspec.
|
|
1408
|
-
// With a detached HEAD and no `branch` there is no name to push, and git's
|
|
1409
|
-
// own error ("You are not currently on a branch") arrives only after the
|
|
1410
|
-
// network handshake — failing here is faster and says what to do.
|
|
1411
|
-
if (target.url !== undefined && branch === null && requestedBranch === undefined) {
|
|
1412
|
-
throw httpError(
|
|
1413
|
-
400,
|
|
1414
|
-
'BAD_REQUEST',
|
|
1415
|
-
'当前处于分离 HEAD 状态,直接推送到 GitHub 仓库需要指定分支名(branch)。',
|
|
1416
|
-
);
|
|
1417
|
-
}
|
|
1418
|
-
|
|
1419
|
-
const result = await runner.push(path, {
|
|
1420
|
-
remote: target.url === undefined ? target.remote : undefined,
|
|
1421
|
-
url: target.url,
|
|
1422
|
-
// NAMED REMOTE: the body's branch, exactly as before — omitting it lets
|
|
1423
|
-
// git apply `push.default`/the configured upstream, which is the
|
|
1424
|
-
// behaviour the existing route has always had.
|
|
1425
|
-
// URL: a URL has no configured merge ref, so the RESOLVED branch (the
|
|
1426
|
-
// body's value, else the branch HEAD points at) must be sent as the
|
|
1427
|
-
// refspec; otherwise `git push <url>` has nothing to push.
|
|
1428
|
-
branch: target.url === undefined ? requestedBranch : (branch ?? undefined),
|
|
1429
|
-
// WHAT LEAVES the repository. Defaults to the branch, but the panel may
|
|
1430
|
-
// ask for a specific version — a commit sha or a tag — which git accepts
|
|
1431
|
-
// as a push source as long as a destination branch is named with it.
|
|
1432
|
-
source: optionalString(body.source),
|
|
1433
|
-
force: optionalBool(body.force, false),
|
|
1434
|
-
setUpstream: optionalBool(body.setUpstream, true),
|
|
1435
|
-
tags: optionalBool(body.tags, false),
|
|
1436
|
-
token: target.token,
|
|
1437
|
-
secrets,
|
|
1438
|
-
});
|
|
1439
|
-
|
|
1440
|
-
// Recorded only after the push actually succeeded: a failed push must not
|
|
1441
|
-
// change what the next click defaults to.
|
|
1442
|
-
if (optionalBool(body.remember, true) !== false) {
|
|
1443
|
-
try {
|
|
1444
|
-
await this.#store.rememberPushTarget(root, branch, {
|
|
1445
|
-
remote: target.remote,
|
|
1446
|
-
owner: target.owner,
|
|
1447
|
-
repo: target.repo,
|
|
1448
|
-
ref: branch ?? '',
|
|
1449
|
-
at: new Date().toISOString(),
|
|
1450
|
-
});
|
|
1451
|
-
} catch {
|
|
1452
|
-
// Bookkeeping must never fail a push the user just completed.
|
|
1453
|
-
}
|
|
1454
|
-
}
|
|
1455
|
-
return { output: result.output };
|
|
1456
|
-
}
|
|
1457
|
-
|
|
1458
|
-
/**
|
|
1459
|
-
* Decide WHERE and WITH WHICH CREDENTIAL one `/local/push` should go.
|
|
1460
|
-
*
|
|
1461
|
-
* Split out of {@link localPush} because the decision has four inputs and two
|
|
1462
|
-
* outputs (destination + token) and is the whole point of CONTRACT §3b.
|
|
1463
|
-
*
|
|
1464
|
-
* @param {object} options
|
|
1465
|
-
* @returns {Promise<{remote: string, url?: string, token?: string,
|
|
1466
|
-
* owner: string, repo: string}>}
|
|
1467
|
-
*/
|
|
1468
|
-
async #resolvePushTarget({ runner, path, root, branch, settings, body, secrets }) {
|
|
1469
|
-
const target = body.target && typeof body.target === 'object' ? body.target : null;
|
|
1470
|
-
|
|
1471
|
-
/* 1. An explicit GitHub repository. */
|
|
1472
|
-
if (target) {
|
|
1473
|
-
const owner = requireString(target, 'owner', '目标仓库的 owner');
|
|
1474
|
-
const repo = requireString(target, 'repo', '目标仓库名称');
|
|
1475
|
-
// Reuse a remote that ALREADY points at this repository. Matching is
|
|
1476
|
-
// case-insensitive because GitHub owners/repos are.
|
|
1477
|
-
const matched = await this.#remoteForRepo(runner, path, owner, repo, secrets);
|
|
1478
|
-
if (matched) {
|
|
1479
|
-
// The reused remote keeps ITS OWN transport: an ssh remote gets no
|
|
1480
|
-
// token (and needs no account), an https one gets the header.
|
|
1481
|
-
const token = await this.#tokenForRemote(runner, path, matched.name);
|
|
1482
|
-
return { remote: matched.name, token, owner, repo };
|
|
1483
|
-
}
|
|
1484
|
-
// No remote → push to the URL directly. `x-access-token` is the
|
|
1485
|
-
// documented https username; the TOKEN itself is never part of the URL
|
|
1486
|
-
// (it would leak through argv, git's error output and any proxy log).
|
|
1487
|
-
const token = await this.#githubHttpsToken(`目标仓库 ${owner}/${repo}`);
|
|
1488
|
-
return { remote: '', url: githubPushUrl(owner, repo), token, owner, repo };
|
|
1489
|
-
}
|
|
1490
|
-
|
|
1491
|
-
/* 2. A named remote. */
|
|
1492
|
-
const explicitRemote = optionalString(body.remote);
|
|
1493
|
-
if (explicitRemote !== undefined) {
|
|
1494
|
-
const token = await this.#tokenForRemote(runner, path, explicitRemote);
|
|
1495
|
-
const parsed = await this.#remoteRepo(runner, path, explicitRemote, secrets);
|
|
1496
|
-
return {
|
|
1497
|
-
remote: explicitRemote,
|
|
1498
|
-
token,
|
|
1499
|
-
owner: parsed?.owner ?? '',
|
|
1500
|
-
repo: parsed?.repo ?? '',
|
|
1501
|
-
};
|
|
1502
|
-
}
|
|
1503
|
-
|
|
1504
|
-
/* 3a. The remembered target for THIS branch. */
|
|
1505
|
-
if (branch !== null) {
|
|
1506
|
-
const memory = await this.#store.pushMemoryFor(root, branch);
|
|
1507
|
-
if (memory) {
|
|
1508
|
-
const remotes = await this.#safeRemotes(runner, path, secrets);
|
|
1509
|
-
// A remembered remote may have been renamed or removed since; only
|
|
1510
|
-
// reuse it when it still exists, otherwise fall back to the URL that
|
|
1511
|
-
// was recorded (it is derived from owner/repo, so nothing is lost).
|
|
1512
|
-
const stillThere = memory.remote !== '' && remotes.some((row) => row.name === memory.remote);
|
|
1513
|
-
if (stillThere) {
|
|
1514
|
-
const token = await this.#tokenForRemote(runner, path, memory.remote);
|
|
1515
|
-
return { remote: memory.remote, token, owner: memory.owner, repo: memory.repo };
|
|
1516
|
-
}
|
|
1517
|
-
if (memory.owner !== '' && memory.repo !== '') {
|
|
1518
|
-
// The remembered destination was a by-URL push, or its remote is
|
|
1519
|
-
// gone: go back to the same repository, still without touching the
|
|
1520
|
-
// configuration.
|
|
1521
|
-
const token = await this.#githubHttpsToken(`记忆的目标仓库 ${memory.owner}/${memory.repo}`);
|
|
1522
|
-
return {
|
|
1523
|
-
remote: '',
|
|
1524
|
-
url: githubPushUrl(memory.owner, memory.repo),
|
|
1525
|
-
token,
|
|
1526
|
-
owner: memory.owner,
|
|
1527
|
-
repo: memory.repo,
|
|
1528
|
-
};
|
|
1529
|
-
}
|
|
1530
|
-
}
|
|
1531
|
-
}
|
|
1532
|
-
|
|
1533
|
-
/* 3b. `settings.defaultRemote`, then `origin`. */
|
|
1534
|
-
const remote = this.#pickRemote(undefined, settings.defaultRemote);
|
|
1535
|
-
const token = await this.#tokenForRemote(runner, path, remote);
|
|
1536
|
-
const parsed = await this.#remoteRepo(runner, path, remote, secrets);
|
|
1537
|
-
return { remote, token, owner: parsed?.owner ?? '', repo: parsed?.repo ?? '' };
|
|
1538
|
-
}
|
|
1539
|
-
|
|
1540
|
-
/**
|
|
1541
|
-
* `git remote -v` as an array, or `[]` when the repository cannot answer.
|
|
1542
|
-
*
|
|
1543
|
-
* `secrets` is passed through so a remote URL that embeds a credential
|
|
1544
|
-
* (`https://user:TOKEN@github.com/…`, which a user can create by hand) is
|
|
1545
|
-
* scrubbed by the runner before it can reach `/push/targets`'s response.
|
|
1546
|
-
*/
|
|
1547
|
-
async #safeRemotes(runner, path, secrets) {
|
|
1548
|
-
try {
|
|
1549
|
-
return (await runner.remotes(path, { secrets })).remotes;
|
|
1550
|
-
} catch {
|
|
1551
|
-
return [];
|
|
1552
|
-
}
|
|
1553
|
-
}
|
|
1554
|
-
|
|
1555
|
-
/** The `{owner, repo}` one named remote points at, or null. */
|
|
1556
|
-
async #remoteRepo(runner, path, remote, secrets) {
|
|
1557
|
-
const remotes = await this.#safeRemotes(runner, path, secrets);
|
|
1558
|
-
const row = remotes.find((candidate) => candidate.name === remote);
|
|
1559
|
-
return row ? parseGithubRemote(row.url) : null;
|
|
1560
|
-
}
|
|
1561
|
-
|
|
1562
|
-
/**
|
|
1563
|
-
* The first remote whose GitHub URL names `owner/repo`, or null.
|
|
1564
|
-
*
|
|
1565
|
-
* Redaction does not break the match: it only masks the userinfo segment
|
|
1566
|
-
* (`https://***@github.com/o/r.git`), and `parseGithubRemote` reads the path.
|
|
1567
|
-
*/
|
|
1568
|
-
async #remoteForRepo(runner, path, owner, repo, secrets) {
|
|
1569
|
-
const remotes = await this.#safeRemotes(runner, path, secrets);
|
|
1570
|
-
for (const row of remotes) {
|
|
1571
|
-
const parsed = parseGithubRemote(row.url);
|
|
1572
|
-
if (!parsed) continue;
|
|
1573
|
-
if (parsed.owner.toLowerCase() === owner.toLowerCase()
|
|
1574
|
-
&& parsed.repo.toLowerCase() === repo.toLowerCase()) {
|
|
1575
|
-
return row;
|
|
1576
|
-
}
|
|
1577
|
-
}
|
|
1578
|
-
return null;
|
|
1579
|
-
}
|
|
1580
|
-
|
|
1581
|
-
/**
|
|
1582
|
-
* `GET /push/targets` — the push-target picker's candidate document
|
|
1583
|
-
* (CONTRACT §3b).
|
|
1584
|
-
*
|
|
1585
|
-
* A directory that is not a repository answers the empty document instead of
|
|
1586
|
-
* failing: the picker is rendered next to the local-status panel, which is
|
|
1587
|
-
* routinely opened on a non-repository workspace.
|
|
1588
|
-
*
|
|
1589
|
-
* @param {{path: string}} query
|
|
1590
|
-
* @returns {Promise<object>}
|
|
1591
|
-
*/
|
|
1592
|
-
async pushTargets(query) {
|
|
1593
|
-
const path = requireString(query, 'path', '仓库路径');
|
|
1594
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1595
|
-
let root;
|
|
1596
|
-
try {
|
|
1597
|
-
root = (await runner.assertRepo(path, { secrets })).root;
|
|
1598
|
-
} catch (error) {
|
|
1599
|
-
if (error?.code === 'NOT_A_REPO') {
|
|
1600
|
-
return { remotes: [], memory: null, branch: null, repoRoot: null };
|
|
1601
|
-
}
|
|
1602
|
-
throw error;
|
|
1603
|
-
}
|
|
1604
|
-
const [remotes, branch] = await Promise.all([
|
|
1605
|
-
this.#safeRemotes(runner, path, secrets),
|
|
1606
|
-
runner.currentBranch(path, { secrets }),
|
|
1607
|
-
]);
|
|
1608
|
-
const memory = branch === null ? null : await this.#store.pushMemoryFor(root, branch);
|
|
1609
|
-
return {
|
|
1610
|
-
remotes: remotes.map((row) => {
|
|
1611
|
-
const parsed = parseGithubRemote(row.url);
|
|
1612
|
-
return {
|
|
1613
|
-
name: row.name,
|
|
1614
|
-
url: row.url,
|
|
1615
|
-
owner: parsed?.owner ?? null,
|
|
1616
|
-
repo: parsed?.repo ?? null,
|
|
1617
|
-
};
|
|
1618
|
-
}),
|
|
1619
|
-
memory,
|
|
1620
|
-
branch,
|
|
1621
|
-
repoRoot: root,
|
|
1622
|
-
};
|
|
1623
|
-
}
|
|
1624
|
-
|
|
1625
|
-
/**
|
|
1626
|
-
* `GET /push/remotes` — the picker's GitHub repository search (CONTRACT §3b).
|
|
1627
|
-
*
|
|
1628
|
-
* Deliberately a SEPARATE mapper from `/repos`: the picker only needs enough
|
|
1629
|
-
* to build a push destination, and reusing the full `RemoteRepo` shape here
|
|
1630
|
-
* would send permissions/avatars the picker never draws.
|
|
1631
|
-
*
|
|
1632
|
-
* @param {{q?: string, page?: string|number}} query
|
|
1633
|
-
* @returns {Promise<{items: object[], page: number, hasMore: boolean}>}
|
|
1634
|
-
*/
|
|
1635
|
-
async pushRemotes(query) {
|
|
1636
|
-
const account = await this.#requireAccount();
|
|
1637
|
-
const page = clampInt(query.page, 1, 1000, 1);
|
|
1638
|
-
const q = optionalString(query.q);
|
|
1639
|
-
const result = q
|
|
1640
|
-
? await searchRepos({ token: account.token, login: account.login, q, page })
|
|
1641
|
-
: await listRepos({ token: account.token, page });
|
|
1642
|
-
await this.#touch(account.id);
|
|
1643
|
-
return {
|
|
1644
|
-
items: result.items.map((repo) => ({
|
|
1645
|
-
fullName: repo.fullName,
|
|
1646
|
-
owner: repo.owner,
|
|
1647
|
-
name: repo.name,
|
|
1648
|
-
private: repo.private,
|
|
1649
|
-
defaultBranch: repo.defaultBranch,
|
|
1650
|
-
cloneUrl: repo.cloneUrl,
|
|
1651
|
-
sshUrl: repo.sshUrl,
|
|
1652
|
-
htmlUrl: repo.htmlUrl,
|
|
1653
|
-
})),
|
|
1654
|
-
page: result.page,
|
|
1655
|
-
hasMore: result.hasMore,
|
|
1656
|
-
};
|
|
1657
|
-
}
|
|
1658
|
-
|
|
1659
|
-
/**
|
|
1660
|
-
* `GET /push/memory` — every remembered target for one repository
|
|
1661
|
-
* (CONTRACT §3b, debug view).
|
|
1662
|
-
*
|
|
1663
|
-
* @param {{path: string}} query
|
|
1664
|
-
* @returns {Promise<{entries: object[]}>}
|
|
1665
|
-
*/
|
|
1666
|
-
async pushMemory(query) {
|
|
1667
|
-
const path = requireString(query, 'path', '仓库路径');
|
|
1668
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1669
|
-
let root;
|
|
1670
|
-
try {
|
|
1671
|
-
root = (await runner.assertRepo(path, { secrets })).root;
|
|
1672
|
-
} catch (error) {
|
|
1673
|
-
if (error?.code === 'NOT_A_REPO') return { entries: [] };
|
|
1674
|
-
throw error;
|
|
1675
|
-
}
|
|
1676
|
-
return { entries: await this.#store.pushMemoryEntries(root) };
|
|
1677
|
-
}
|
|
1678
|
-
|
|
1679
|
-
/**
|
|
1680
|
-
* `POST /local/push/target/forget` — drop one branch's remembered target.
|
|
1681
|
-
*
|
|
1682
|
-
* Not in CONTRACT §3b's table, and OPTIONAL for the client: it exists because
|
|
1683
|
-
* a remembered target that has become wrong (pushed to the wrong fork once)
|
|
1684
|
-
* would otherwise be permanent from inside the panel.
|
|
1685
|
-
*
|
|
1686
|
-
* @param {object} body
|
|
1687
|
-
* @returns {Promise<{forgotten: boolean}>}
|
|
1688
|
-
*/
|
|
1689
|
-
async localForgetPushTarget(body) {
|
|
1690
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1691
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1692
|
-
const root = (await runner.assertRepo(path, { secrets })).root;
|
|
1693
|
-
const branch = optionalString(body.branch)
|
|
1694
|
-
?? (await runner.currentBranch(path, { secrets }));
|
|
1695
|
-
if (branch === null) throw httpError(400, 'BAD_REQUEST', '当前处于分离 HEAD 状态,请指定分支名');
|
|
1696
|
-
return { forgotten: await this.#store.forgetPushTarget(root, branch) };
|
|
1697
|
-
}
|
|
1698
|
-
|
|
1699
|
-
/**
|
|
1700
|
-
* `POST /local/commit`.
|
|
1701
|
-
* @param {object} body
|
|
1702
|
-
* @returns {Promise<{output: string}>}
|
|
1703
|
-
*/
|
|
1704
|
-
async localCommit(body) {
|
|
1705
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1706
|
-
const message = requireString(body, 'message', '提交信息');
|
|
1707
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1708
|
-
const files = Array.isArray(body.files)
|
|
1709
|
-
? body.files.filter((file) => typeof file === 'string' && file !== '')
|
|
1710
|
-
: undefined;
|
|
1711
|
-
const result = await runner.commit(path, {
|
|
1712
|
-
message,
|
|
1713
|
-
all: optionalBool(body.all, true),
|
|
1714
|
-
files,
|
|
1715
|
-
secrets,
|
|
1716
|
-
});
|
|
1717
|
-
return { output: result.output };
|
|
1718
|
-
}
|
|
1719
|
-
|
|
1720
|
-
/**
|
|
1721
|
-
* `POST /local/checkout`.
|
|
1722
|
-
* @param {object} body
|
|
1723
|
-
* @returns {Promise<{output: string}>}
|
|
1724
|
-
*/
|
|
1725
|
-
async localCheckout(body) {
|
|
1726
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1727
|
-
const ref = requireString(body, 'ref', '要切换的分支或提交');
|
|
1728
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1729
|
-
const result = await runner.checkout(path, {
|
|
1730
|
-
ref,
|
|
1731
|
-
create: optionalBool(body.create, false),
|
|
1732
|
-
secrets,
|
|
1733
|
-
});
|
|
1734
|
-
return { output: result.output };
|
|
1735
|
-
}
|
|
1736
|
-
|
|
1737
|
-
/**
|
|
1738
|
-
* `POST /local/branch`.
|
|
1739
|
-
* @param {object} body
|
|
1740
|
-
* @returns {Promise<{output: string}>}
|
|
1741
|
-
*/
|
|
1742
|
-
async localBranch(body) {
|
|
1743
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1744
|
-
const name = requireString(body, 'name', '分支名');
|
|
1745
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1746
|
-
const result = await runner.createBranch(path, {
|
|
1747
|
-
name,
|
|
1748
|
-
from: optionalString(body.from),
|
|
1749
|
-
checkout: optionalBool(body.checkout, true),
|
|
1750
|
-
secrets,
|
|
1751
|
-
});
|
|
1752
|
-
return { output: result.output };
|
|
1753
|
-
}
|
|
1754
|
-
|
|
1755
|
-
/**
|
|
1756
|
-
* `POST /local/branch/delete`.
|
|
1757
|
-
* @param {object} body
|
|
1758
|
-
* @returns {Promise<{output: string}>}
|
|
1759
|
-
*/
|
|
1760
|
-
async localBranchDelete(body) {
|
|
1761
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1762
|
-
const name = requireString(body, 'name', '分支名');
|
|
1763
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1764
|
-
const result = await runner.deleteBranch(path, {
|
|
1765
|
-
name,
|
|
1766
|
-
force: optionalBool(body.force, false),
|
|
1767
|
-
secrets,
|
|
1768
|
-
});
|
|
1769
|
-
return { output: result.output };
|
|
1770
|
-
}
|
|
1771
|
-
|
|
1772
|
-
/**
|
|
1773
|
-
* `POST /local/merge`.
|
|
1774
|
-
* @param {object} body
|
|
1775
|
-
* @returns {Promise<{output: string}>}
|
|
1776
|
-
*/
|
|
1777
|
-
async localMerge(body) {
|
|
1778
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1779
|
-
const ref = requireString(body, 'ref', '要合并的分支或提交');
|
|
1780
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1781
|
-
const result = await runner.merge(path, { ref, secrets });
|
|
1782
|
-
return { output: result.output };
|
|
1783
|
-
}
|
|
1784
|
-
|
|
1785
|
-
/**
|
|
1786
|
-
* `POST /local/reset` — `mode: 'hard'` is destructive, so it needs `confirm`.
|
|
1787
|
-
* @param {object} body
|
|
1788
|
-
* @returns {Promise<{output: string}>}
|
|
1789
|
-
*/
|
|
1790
|
-
async localReset(body) {
|
|
1791
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1792
|
-
const mode = body.mode === 'soft' || body.mode === 'hard' ? body.mode : 'mixed';
|
|
1793
|
-
if (mode === 'hard' && optionalBool(body.confirm, false) !== true) {
|
|
1794
|
-
throw httpError(409, 'CONFLICT', '硬重置会永久丢弃所有未提交的改动,请确认后再执行(confirm: true)。');
|
|
1795
|
-
}
|
|
1796
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1797
|
-
const result = await runner.reset(path, {
|
|
1798
|
-
ref: optionalString(body.ref) ?? 'HEAD',
|
|
1799
|
-
mode,
|
|
1800
|
-
secrets,
|
|
1801
|
-
});
|
|
1802
|
-
return { output: result.output };
|
|
1803
|
-
}
|
|
1804
|
-
|
|
1805
|
-
/**
|
|
1806
|
-
* `POST /local/revert` and `POST /local/revert-commit`.
|
|
1807
|
-
*
|
|
1808
|
-
* Both routes undo one commit by REVERTING it (a new commit), never by
|
|
1809
|
-
* rewinding history: the contract's two rows describe the same undo, and the
|
|
1810
|
-
* non-destructive form is the one that cannot lose already-pushed work.
|
|
1811
|
-
* @param {object} body
|
|
1812
|
-
* @returns {Promise<{output: string}>}
|
|
1813
|
-
*/
|
|
1814
|
-
async localRevert(body) {
|
|
1815
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1816
|
-
const sha = requireString(body, 'sha', '提交 SHA');
|
|
1817
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1818
|
-
const result = await runner.revert(path, { sha, secrets });
|
|
1819
|
-
return { output: result.output };
|
|
1820
|
-
}
|
|
1821
|
-
|
|
1822
|
-
/**
|
|
1823
|
-
* `POST /local/tag`.
|
|
1824
|
-
* @param {object} body
|
|
1825
|
-
* @returns {Promise<{output: string}>}
|
|
1826
|
-
*/
|
|
1827
|
-
async localTag(body) {
|
|
1828
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1829
|
-
const name = requireString(body, 'name', '标签名');
|
|
1830
|
-
const { settings, runner, secrets } = await this.#runnerAndSecrets();
|
|
1831
|
-
const remote = this.#pickRemote(body.remote, settings.defaultRemote);
|
|
1832
|
-
const wantsPush = optionalBool(body.push, false);
|
|
1833
|
-
const token = wantsPush ? await this.#tokenForRemote(runner, path, remote) : undefined;
|
|
1834
|
-
const result = await runner.tag(path, {
|
|
1835
|
-
name,
|
|
1836
|
-
ref: optionalString(body.ref) ?? 'HEAD',
|
|
1837
|
-
push: wantsPush,
|
|
1838
|
-
remote,
|
|
1839
|
-
token,
|
|
1840
|
-
secrets,
|
|
1841
|
-
});
|
|
1842
|
-
return { output: result.output };
|
|
1843
|
-
}
|
|
1844
|
-
|
|
1845
|
-
/**
|
|
1846
|
-
* `POST /local/stash`.
|
|
1847
|
-
* @param {object} body
|
|
1848
|
-
* @returns {Promise<{output: string}>}
|
|
1849
|
-
*/
|
|
1850
|
-
async localStash(body) {
|
|
1851
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1852
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1853
|
-
const result = await runner.stash(path, {
|
|
1854
|
-
message: optionalString(body.message),
|
|
1855
|
-
includeUntracked: optionalBool(body.includeUntracked, true),
|
|
1856
|
-
secrets,
|
|
1857
|
-
});
|
|
1858
|
-
return { output: result.output };
|
|
1859
|
-
}
|
|
1860
|
-
|
|
1861
|
-
/**
|
|
1862
|
-
* `POST /local/stash/pop`.
|
|
1863
|
-
* @param {object} body
|
|
1864
|
-
* @returns {Promise<{output: string}>}
|
|
1865
|
-
*/
|
|
1866
|
-
async localStashPop(body) {
|
|
1867
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1868
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1869
|
-
const result = await runner.stashPop(path, {
|
|
1870
|
-
index: clampInt(body.index, 0, 999, 0),
|
|
1871
|
-
secrets,
|
|
1872
|
-
});
|
|
1873
|
-
return { output: result.output };
|
|
1874
|
-
}
|
|
1875
|
-
|
|
1876
|
-
/**
|
|
1877
|
-
* `POST /local/restore`.
|
|
1878
|
-
* @param {object} body
|
|
1879
|
-
* @returns {Promise<{output: string}>}
|
|
1880
|
-
*/
|
|
1881
|
-
async localRestore(body) {
|
|
1882
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1883
|
-
const files = Array.isArray(body.files) ? body.files : [];
|
|
1884
|
-
if (files.length === 0) throw httpError(400, 'BAD_REQUEST', '缺少要还原的文件');
|
|
1885
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1886
|
-
const result = await runner.restore(path, {
|
|
1887
|
-
files,
|
|
1888
|
-
staged: optionalBool(body.staged, false),
|
|
1889
|
-
secrets,
|
|
1890
|
-
});
|
|
1891
|
-
return { output: result.output };
|
|
1892
|
-
}
|
|
1893
|
-
|
|
1894
|
-
/**
|
|
1895
|
-
* `POST /local/discard-all` — destructive; requires `confirm: true`.
|
|
1896
|
-
* @param {object} body
|
|
1897
|
-
* @returns {Promise<{output: string}>}
|
|
1898
|
-
*/
|
|
1899
|
-
async localDiscardAll(body) {
|
|
1900
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
1901
|
-
if (optionalBool(body.confirm, false) !== true) {
|
|
1902
|
-
throw httpError(409, 'CONFLICT', '丢弃全部改动会永久删除所有未提交内容(含未跟踪文件),请确认后再执行(confirm: true)。');
|
|
1903
|
-
}
|
|
1904
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
1905
|
-
const result = await runner.discardAll(path, { secrets });
|
|
1906
|
-
return { output: result.output };
|
|
1907
|
-
}
|
|
1908
|
-
|
|
1909
|
-
/* ---------------- CONTRACT §4: the agent tool ---------------- */
|
|
1910
|
-
|
|
1911
|
-
/**
|
|
1912
|
-
* One `github_link` tool call. Every arm delegates to a method above, so the
|
|
1913
|
-
* model and the browser can never diverge.
|
|
1914
|
-
*
|
|
1915
|
-
* @param {{action: string, path?: string, message?: string, remote?: string,
|
|
1916
|
-
* branch?: string, limit?: number, force?: boolean, q?: string,
|
|
1917
|
-
* page?: number}} args
|
|
1918
|
-
* @param {{resolvePath?: () => Promise<string>}} context
|
|
1919
|
-
* @returns {Promise<object>} the tool's canonical output value.
|
|
1920
|
-
*/
|
|
1921
|
-
/**
|
|
1922
|
-
* Which repository a tool-initiated release should land in.
|
|
1923
|
-
*
|
|
1924
|
-
* An explicit owner/repo wins; otherwise the working directory's own GitHub
|
|
1925
|
-
* remote decides, because "publish this checkout" is what the caller means.
|
|
1926
|
-
* Guessing a repository would be worse than failing, so an unattached
|
|
1927
|
-
* directory gets a clear instruction instead.
|
|
1928
|
-
*
|
|
1929
|
-
* @param {string} path repository path.
|
|
1930
|
-
* @param {object} args tool arguments (`owner`, `repo`).
|
|
1931
|
-
* @returns {Promise<{owner: string, repo: string}>}
|
|
1932
|
-
*/
|
|
1933
|
-
async #toolReleaseTarget(path, args) {
|
|
1934
|
-
const explicitOwner = optionalString(args?.owner);
|
|
1935
|
-
const explicitRepo = optionalString(args?.repo);
|
|
1936
|
-
if (explicitOwner && explicitRepo) return { owner: explicitOwner, repo: explicitRepo };
|
|
1937
|
-
const status = await this.localStatus(path);
|
|
1938
|
-
if (!status.isRepo) {
|
|
1939
|
-
throw httpError(400, 'NOT_A_REPO', `${status.root ?? path} 不是 Git 仓库,无法推断要发布到哪个仓库。`);
|
|
1940
|
-
}
|
|
1941
|
-
if (status.githubRemote && status.githubRemote.owner && status.githubRemote.repo) {
|
|
1942
|
-
return { owner: status.githubRemote.owner, repo: status.githubRemote.repo };
|
|
1943
|
-
}
|
|
1944
|
-
throw httpError(
|
|
1945
|
-
400,
|
|
1946
|
-
'BAD_REQUEST',
|
|
1947
|
-
'当前工作区没有关联 GitHub 远端,无法推断要发布到哪个仓库;请传 owner 与 repo,或先用 /local/remote 关联远端。',
|
|
1948
|
-
);
|
|
1949
|
-
}
|
|
1950
|
-
|
|
1951
|
-
async toolCall(args, context = {}) {
|
|
1952
|
-
const action = String(args?.action ?? '');
|
|
1953
|
-
const cwd = async () => {
|
|
1954
|
-
const explicit = optionalString(args?.path);
|
|
1955
|
-
if (explicit) return explicit;
|
|
1956
|
-
if (typeof context.resolvePath === 'function') {
|
|
1957
|
-
const resolved = await context.resolvePath();
|
|
1958
|
-
if (typeof resolved === 'string' && resolved !== '') return resolved;
|
|
1959
|
-
}
|
|
1960
|
-
return process.cwd();
|
|
1961
|
-
};
|
|
1962
|
-
switch (action) {
|
|
1963
|
-
case 'status': {
|
|
1964
|
-
return { action, status: await this.localStatus(await cwd()) };
|
|
1965
|
-
}
|
|
1966
|
-
case 'log': {
|
|
1967
|
-
const window = await this.localLog({ path: await cwd(), limit: args?.limit });
|
|
1968
|
-
return { action, ...window };
|
|
1969
|
-
}
|
|
1970
|
-
case 'push': {
|
|
1971
|
-
// A named repository replaces the local remote, matching what the
|
|
1972
|
-
// panel's picker does; without this the agent could only push to a
|
|
1973
|
-
// remote a human had already configured.
|
|
1974
|
-
const owner = optionalString(args?.owner);
|
|
1975
|
-
const repo = optionalString(args?.repo);
|
|
1976
|
-
const target = owner && repo ? { owner, repo } : undefined;
|
|
1977
|
-
const result = await this.localPush({
|
|
1978
|
-
path: await cwd(),
|
|
1979
|
-
remote: target ? undefined : optionalString(args?.remote),
|
|
1980
|
-
target,
|
|
1981
|
-
branch: optionalString(args?.branch),
|
|
1982
|
-
force: optionalBool(args?.force, false),
|
|
1983
|
-
});
|
|
1984
|
-
return { action, output: result.output };
|
|
1985
|
-
}
|
|
1986
|
-
case 'pull': {
|
|
1987
|
-
const result = await this.localPull({
|
|
1988
|
-
path: await cwd(),
|
|
1989
|
-
remote: optionalString(args?.remote),
|
|
1990
|
-
branch: optionalString(args?.branch),
|
|
1991
|
-
});
|
|
1992
|
-
return { action, output: result.output };
|
|
1993
|
-
}
|
|
1994
|
-
case 'commit': {
|
|
1995
|
-
const result = await this.localCommit({
|
|
1996
|
-
path: await cwd(),
|
|
1997
|
-
message: requireString(args, 'message', '提交信息'),
|
|
1998
|
-
all: true,
|
|
1999
|
-
});
|
|
2000
|
-
return { action, output: result.output };
|
|
2001
|
-
}
|
|
2002
|
-
case 'repos': {
|
|
2003
|
-
const result = await this.repos({ page: args?.page, q: optionalString(args?.q) });
|
|
2004
|
-
return {
|
|
2005
|
-
action,
|
|
2006
|
-
page: result.page,
|
|
2007
|
-
hasMore: result.hasMore,
|
|
2008
|
-
repos: result.items.map((repo) => ({
|
|
2009
|
-
fullName: repo.fullName,
|
|
2010
|
-
private: repo.private,
|
|
2011
|
-
defaultBranch: repo.defaultBranch,
|
|
2012
|
-
updatedAt: repo.updatedAt,
|
|
2013
|
-
htmlUrl: repo.htmlUrl,
|
|
2014
|
-
})),
|
|
2015
|
-
};
|
|
2016
|
-
}
|
|
2017
|
-
case 'accounts': {
|
|
2018
|
-
const state = await this.state();
|
|
2019
|
-
return {
|
|
2020
|
-
action,
|
|
2021
|
-
activeAccountId: state.activeAccountId,
|
|
2022
|
-
accounts: state.accounts.map((account) => ({
|
|
2023
|
-
id: account.id,
|
|
2024
|
-
login: account.login,
|
|
2025
|
-
tokenKind: account.tokenKind,
|
|
2026
|
-
scopes: account.scopes,
|
|
2027
|
-
})),
|
|
2028
|
-
};
|
|
2029
|
-
}
|
|
2030
|
-
case 'create_repo': {
|
|
2031
|
-
// Creating the remote is what makes the very first push possible, so
|
|
2032
|
-
// the agent needs it: without this it could only push to a repository
|
|
2033
|
-
// a human had already made by hand.
|
|
2034
|
-
const result = await this.repoCreate({
|
|
2035
|
-
name: requireString(args, 'repoName', '仓库名'),
|
|
2036
|
-
private: optionalBool(args?.isPrivate, true),
|
|
2037
|
-
description: optionalString(args?.description) ?? '',
|
|
2038
|
-
autoInit: optionalBool(args?.autoInit, false),
|
|
2039
|
-
});
|
|
2040
|
-
return {
|
|
2041
|
-
action,
|
|
2042
|
-
repo: {
|
|
2043
|
-
fullName: result.repo.fullName,
|
|
2044
|
-
private: result.repo.private,
|
|
2045
|
-
defaultBranch: result.repo.defaultBranch,
|
|
2046
|
-
htmlUrl: result.repo.htmlUrl,
|
|
2047
|
-
cloneUrl: result.repo.cloneUrl,
|
|
2048
|
-
},
|
|
2049
|
-
};
|
|
2050
|
-
}
|
|
2051
|
-
case 'release': {
|
|
2052
|
-
// Which repository this lands in: the argument, else the GitHub remote
|
|
2053
|
-
// the working directory is already attached to. Resolving it from the
|
|
2054
|
-
// remote is what lets the agent "publish this checkout".
|
|
2055
|
-
const tagName = requireString(args, 'tagName', '标签名');
|
|
2056
|
-
const target = await this.#toolReleaseTarget(await cwd(), args);
|
|
2057
|
-
const result = await this.releaseCreate({
|
|
2058
|
-
owner: target.owner,
|
|
2059
|
-
repo: target.repo,
|
|
2060
|
-
tagName,
|
|
2061
|
-
name: optionalString(args?.releaseName) ?? tagName,
|
|
2062
|
-
body: optionalString(args?.releaseBody) ?? '',
|
|
2063
|
-
target: optionalString(args?.branch),
|
|
2064
|
-
draft: optionalBool(args?.draft, false),
|
|
2065
|
-
prerelease: optionalBool(args?.prerelease, false),
|
|
2066
|
-
});
|
|
2067
|
-
return {
|
|
2068
|
-
action,
|
|
2069
|
-
release: {
|
|
2070
|
-
id: result.release.id,
|
|
2071
|
-
tagName: result.release.tagName,
|
|
2072
|
-
name: result.release.name,
|
|
2073
|
-
draft: result.release.draft,
|
|
2074
|
-
htmlUrl: result.release.htmlUrl,
|
|
2075
|
-
},
|
|
2076
|
-
};
|
|
2077
|
-
}
|
|
2078
|
-
case 'review': {
|
|
2079
|
-
// NEVER run a review on the model's own initiative: the user must see
|
|
2080
|
-
// the dialog and choose what is inspected. Record a request; the panel
|
|
2081
|
-
// picks it up and opens the normal review dialog.
|
|
2082
|
-
const presetIds = Array.isArray(args?.presetIds)
|
|
2083
|
-
? args.presetIds.filter((id) => typeof id === 'string' && id !== '')
|
|
2084
|
-
: [];
|
|
2085
|
-
const raised = this.#raiseReviewRequest({
|
|
2086
|
-
path: await cwd(),
|
|
2087
|
-
presetIds,
|
|
2088
|
-
customPrompt: optionalString(args?.customPrompt) ?? '',
|
|
2089
|
-
source: 'agent',
|
|
2090
|
-
});
|
|
2091
|
-
return { action, reviewRequest: raised };
|
|
2092
|
-
}
|
|
2093
|
-
default:
|
|
2094
|
-
throw httpError(
|
|
2095
|
-
400,
|
|
2096
|
-
'BAD_REQUEST',
|
|
2097
|
-
`未知 action「${action}」;可用:status、log、push、pull、commit、repos、accounts、create_repo、release、review。`,
|
|
2098
|
-
);
|
|
2099
|
-
}
|
|
2100
|
-
}
|
|
2101
|
-
|
|
2102
|
-
/**
|
|
2103
|
-
* One `cloudflare` tool call. Every arm delegates to a method above, so the
|
|
2104
|
-
* model and the panel can never diverge (one operation, two callers).
|
|
2105
|
-
*
|
|
2106
|
-
* @param {object} args
|
|
2107
|
-
* @param {{resolvePath?: () => Promise<string>}} context
|
|
2108
|
-
* @returns {Promise<object>}
|
|
2109
|
-
*/
|
|
2110
|
-
async cloudflareToolCall(args, context = {}) {
|
|
2111
|
-
const action = String(args?.action ?? '');
|
|
2112
|
-
const cwd = async () => {
|
|
2113
|
-
const explicit = optionalString(args?.path);
|
|
2114
|
-
if (explicit) return explicit;
|
|
2115
|
-
if (typeof context.resolvePath === 'function') {
|
|
2116
|
-
const resolved = await context.resolvePath();
|
|
2117
|
-
if (typeof resolved === 'string' && resolved !== '') return resolved;
|
|
2118
|
-
}
|
|
2119
|
-
return process.cwd();
|
|
2120
|
-
};
|
|
2121
|
-
switch (action) {
|
|
2122
|
-
case 'accounts': {
|
|
2123
|
-
const data = await this.cloudflareAccounts();
|
|
2124
|
-
return { action, ...data };
|
|
2125
|
-
}
|
|
2126
|
-
case 'overview': {
|
|
2127
|
-
const data = await this.cloudflareOverview();
|
|
2128
|
-
return { action, ...data };
|
|
2129
|
-
}
|
|
2130
|
-
case 'projects': {
|
|
2131
|
-
const data = await this.cloudflareProjects();
|
|
2132
|
-
return { action, ...data };
|
|
2133
|
-
}
|
|
2134
|
-
case 'workers': {
|
|
2135
|
-
const data = await this.cloudflareWorkers();
|
|
2136
|
-
return { action, ...data };
|
|
2137
|
-
}
|
|
2138
|
-
case 'zones': {
|
|
2139
|
-
const data = await this.cloudflareZones();
|
|
2140
|
-
return { action, ...data };
|
|
2141
|
-
}
|
|
2142
|
-
case 'detect': {
|
|
2143
|
-
const data = await this.cloudflareDetect({ path: await cwd() });
|
|
2144
|
-
return { action, ...data };
|
|
2145
|
-
}
|
|
2146
|
-
case 'deploy': {
|
|
2147
|
-
const data = await this.cloudflareDeploy({
|
|
2148
|
-
path: await cwd(),
|
|
2149
|
-
kind: optionalString(args?.kind),
|
|
2150
|
-
project: optionalString(args?.project),
|
|
2151
|
-
name: optionalString(args?.name),
|
|
2152
|
-
});
|
|
2153
|
-
return { action, ...data };
|
|
2154
|
-
}
|
|
2155
|
-
case 'review': {
|
|
2156
|
-
const data = await this.cloudflareReview({
|
|
2157
|
-
path: await cwd(),
|
|
2158
|
-
kind: optionalString(args?.kind),
|
|
2159
|
-
presetIds: Array.isArray(args?.presetIds) ? args.presetIds : [],
|
|
2160
|
-
customPrompt: optionalString(args?.customPrompt) ?? '',
|
|
2161
|
-
});
|
|
2162
|
-
return { action, ...data };
|
|
2163
|
-
}
|
|
2164
|
-
default:
|
|
2165
|
-
throw httpError(
|
|
2166
|
-
400,
|
|
2167
|
-
'BAD_REQUEST',
|
|
2168
|
-
`未知 action「${action}」;可用:accounts、overview、projects、workers、zones、detect、deploy、review。`,
|
|
2169
|
-
);
|
|
2170
|
-
}
|
|
2171
|
-
}
|
|
2172
|
-
|
|
2173
|
-
/* ---------------- repository information (languages + assets) ---------------- */
|
|
2174
|
-
|
|
2175
|
-
/**
|
|
2176
|
-
* `GET /repos/languages` — the byte/percentage breakdown the cards bar uses.
|
|
2177
|
-
*
|
|
2178
|
-
* A failure here must not break a repository list, so a scope or network
|
|
2179
|
-
* problem degrades to an empty list with a warning rather than an error.
|
|
2180
|
-
*
|
|
2181
|
-
* @param {{owner: string, name: string}} query
|
|
2182
|
-
* @returns {Promise<{items: object[]}>}
|
|
2183
|
-
*/
|
|
2184
|
-
async repoLanguages(query) {
|
|
2185
|
-
const account = await this.#requireAccount();
|
|
2186
|
-
const owner = requireString(query, 'owner', ' owner');
|
|
2187
|
-
const name = requireString(query, 'name', ' name');
|
|
2188
|
-
try {
|
|
2189
|
-
const result = await repoLanguages({ token: account.token, owner, name });
|
|
2190
|
-
await this.#touch(account.id);
|
|
2191
|
-
return result;
|
|
2192
|
-
} catch (error) {
|
|
2193
|
-
// Degrade: the card simply renders without the language bar.
|
|
2194
|
-
if (error && (error.code === 'UNAUTHORIZED' || error.code === 'NOT_FOUND')) {
|
|
2195
|
-
return { items: [], warning: '无法读取语言构成(权限或仓库不可见)。' };
|
|
2196
|
-
}
|
|
2197
|
-
throw error;
|
|
2198
|
-
}
|
|
2199
|
-
}
|
|
2200
|
-
|
|
2201
|
-
/**
|
|
2202
|
-
* `POST /releases/asset/delete` — remove one uploaded asset.
|
|
2203
|
-
*
|
|
2204
|
-
* @param {object} body
|
|
2205
|
-
* @returns {Promise<{deleted: true}>}
|
|
2206
|
-
*/
|
|
2207
|
-
async releaseAssetDelete(body) {
|
|
2208
|
-
const account = await this.#requireAccount();
|
|
2209
|
-
const owner = requireString(body, 'owner', ' owner');
|
|
2210
|
-
const name = requireString(body, 'name', '仓库名称');
|
|
2211
|
-
const assetId = requireString(body, 'assetId', '附件 id');
|
|
2212
|
-
const result = await deleteReleaseAsset({
|
|
2213
|
-
token: account.token,
|
|
2214
|
-
owner,
|
|
2215
|
-
name,
|
|
2216
|
-
assetId,
|
|
2217
|
-
});
|
|
2218
|
-
await this.#touch(account.id);
|
|
2219
|
-
return result;
|
|
2220
|
-
}
|
|
2221
|
-
/**
|
|
2222
|
-
* `POST /releases/asset` — attach a file to a release.
|
|
2223
|
-
*
|
|
2224
|
-
* The body carries base64 because the transport is JSON. Uploads are the one
|
|
2225
|
-
* place where a size cap matters: GitHub rejects assets over 2 GB, and
|
|
2226
|
-
* buffering an arbitrary file in memory would be worse, so the cap is applied
|
|
2227
|
-
* here with a Chinese explanation.
|
|
2228
|
-
*
|
|
2229
|
-
* @param {object} body
|
|
2230
|
-
* @returns {Promise<{asset: object}>}
|
|
2231
|
-
*/
|
|
2232
|
-
async releaseAssetUpload(body) {
|
|
2233
|
-
const account = await this.#requireAccount();
|
|
2234
|
-
const owner = requireString(body, 'owner', ' owner');
|
|
2235
|
-
const name = requireString(body, 'name', '仓库名称');
|
|
2236
|
-
const releaseId = requireString(body, 'releaseId', '发布 id');
|
|
2237
|
-
const fileName = requireString(body, 'fileName', '文件名');
|
|
2238
|
-
const base64 = requireString(body, 'base64', '文件内容');
|
|
2239
|
-
const bytes = Buffer.from(base64, 'base64');
|
|
2240
|
-
if (bytes.length === 0) throw httpError(400, 'BAD_REQUEST', '文件内容为空。');
|
|
2241
|
-
const MAX_BYTES = 200 * 1024 * 1024;
|
|
2242
|
-
if (bytes.length > MAX_BYTES) {
|
|
2243
|
-
throw httpError(
|
|
2244
|
-
400,
|
|
2245
|
-
'BAD_REQUEST',
|
|
2246
|
-
`附件超过 ${MAX_BYTES / 1024 / 1024} MB,请改用更小的文件或分卷发布。`,
|
|
2247
|
-
);
|
|
2248
|
-
}
|
|
2249
|
-
const result = await uploadReleaseAsset({
|
|
2250
|
-
token: account.token,
|
|
2251
|
-
owner,
|
|
2252
|
-
name,
|
|
2253
|
-
releaseId,
|
|
2254
|
-
fileName,
|
|
2255
|
-
bytes,
|
|
2256
|
-
contentType: optionalString(body.contentType),
|
|
2257
|
-
});
|
|
2258
|
-
await this.#touch(account.id);
|
|
2259
|
-
return result;
|
|
2260
|
-
}
|
|
2261
|
-
|
|
2262
|
-
/**
|
|
2263
|
-
* `GET /diagnostics` — why can (or can't) the agent call this plugin?
|
|
2264
|
-
*
|
|
2265
|
-
* The agent tool is an optional surface, and a registration failure is
|
|
2266
|
-
* otherwise invisible: the model simply never sees the tool. This reports
|
|
2267
|
-
* the recorded outcome plus a live probe, so the answer is a fact rather
|
|
2268
|
-
* than a guess.
|
|
2269
|
-
*
|
|
2270
|
-
* @returns {Promise<object>}
|
|
2271
|
-
*/
|
|
2272
|
-
async diagnostics() {
|
|
2273
|
-
const ctx = this.ctx;
|
|
2274
|
-
let tools = null;
|
|
2275
|
-
try {
|
|
2276
|
-
tools = typeof ctx.get === 'function' ? ctx.get('tools') : ctx.tools;
|
|
2277
|
-
} catch {
|
|
2278
|
-
tools = null;
|
|
2279
|
-
}
|
|
2280
|
-
let visible = false;
|
|
2281
|
-
let toolNames = [];
|
|
2282
|
-
if (tools && typeof tools.get === 'function') {
|
|
2283
|
-
try {
|
|
2284
|
-
visible = Boolean(tools.get('github_link'));
|
|
2285
|
-
} catch {
|
|
2286
|
-
visible = false;
|
|
2287
|
-
}
|
|
2288
|
-
}
|
|
2289
|
-
if (tools && typeof tools.schemas === 'function') {
|
|
2290
|
-
try {
|
|
2291
|
-
toolNames = (tools.schemas() || [])
|
|
2292
|
-
.map((schema) => (schema && schema.name ? schema.name : ''))
|
|
2293
|
-
.filter((name) => name === 'github_link');
|
|
2294
|
-
} catch {
|
|
2295
|
-
toolNames = [];
|
|
2296
|
-
}
|
|
2297
|
-
}
|
|
2298
|
-
return {
|
|
2299
|
-
toolsService: tools ? 'present' : 'absent',
|
|
2300
|
-
tool: {
|
|
2301
|
-
name: 'github_link',
|
|
2302
|
-
attempted: toolRegistration.attempted,
|
|
2303
|
-
registered: toolRegistration.registered,
|
|
2304
|
-
visible,
|
|
2305
|
-
inSchemas: toolNames.length > 0,
|
|
2306
|
-
error: toolRegistration.error,
|
|
2307
|
-
},
|
|
2308
|
-
};
|
|
2309
|
-
}
|
|
2310
|
-
/* ---------------- review request gate (agent must ask a human) ---------------- */
|
|
2311
|
-
|
|
2312
|
-
/**
|
|
2313
|
-
* Record an agent-initiated review request for the panel to confirm.
|
|
2314
|
-
*
|
|
2315
|
-
* One slot only. A second request while one is waiting is answered with
|
|
2316
|
-
* `alreadyPending`, which is what stops an agent from re-requesting in a
|
|
2317
|
-
* loop when the user has simply not clicked yet.
|
|
2318
|
-
*
|
|
2319
|
-
* @param {{path: string, presetIds: string[], customPrompt: string, source: string}} request
|
|
2320
|
-
* @returns {object}
|
|
2321
|
-
*/
|
|
2322
|
-
#raiseReviewRequest(request) {
|
|
2323
|
-
if (this.#reviewRequest) {
|
|
2324
|
-
return {
|
|
2325
|
-
status: 'already_pending',
|
|
2326
|
-
message: '已有一个待确认的审查请求,用户尚未在界面中确认。不要重复请求,也不要自行执行审查。',
|
|
2327
|
-
pending: this.#publicReviewRequest(),
|
|
2328
|
-
};
|
|
2329
|
-
}
|
|
2330
|
-
this.#reviewRequest = {
|
|
2331
|
-
id: `rvreq_${Date.now().toString(36)}`,
|
|
2332
|
-
path: String(request.path ?? ''),
|
|
2333
|
-
presetIds: Array.isArray(request.presetIds) ? request.presetIds : [],
|
|
2334
|
-
customPrompt: String(request.customPrompt ?? ''),
|
|
2335
|
-
source: String(request.source ?? 'agent'),
|
|
2336
|
-
createdAt: Date.now(),
|
|
2337
|
-
};
|
|
2338
|
-
return {
|
|
2339
|
-
status: 'awaiting_user',
|
|
2340
|
-
message: '已在界面中打开审查配置窗口,等待用户选择审查项。在用户确认并开始之前,不要再次调用 review,也不要用其他方式自行执行审查。',
|
|
2341
|
-
pending: this.#publicReviewRequest(),
|
|
2342
|
-
};
|
|
2343
|
-
}
|
|
2344
|
-
|
|
2345
|
-
/** The pending request in a shape the client can render. */
|
|
2346
|
-
#publicReviewRequest() {
|
|
2347
|
-
const request = this.#reviewRequest;
|
|
2348
|
-
if (!request) return null;
|
|
2349
|
-
return {
|
|
2350
|
-
id: request.id,
|
|
2351
|
-
path: request.path,
|
|
2352
|
-
presetIds: [...request.presetIds],
|
|
2353
|
-
customPrompt: request.customPrompt,
|
|
2354
|
-
source: request.source,
|
|
2355
|
-
createdAt: request.createdAt,
|
|
2356
|
-
};
|
|
2357
|
-
}
|
|
2358
|
-
|
|
2359
|
-
/**
|
|
2360
|
-
* `GET /review/pending` — what the panel polls to know it must open the dialog.
|
|
2361
|
-
* @returns {Promise<{pending: object|null}>}
|
|
2362
|
-
*/
|
|
2363
|
-
async reviewPending() {
|
|
2364
|
-
return { pending: this.#publicReviewRequest() };
|
|
2365
|
-
}
|
|
2366
|
-
|
|
2367
|
-
/**
|
|
2368
|
-
* `POST /review/pending/clear` — the user answered the request (started it,
|
|
2369
|
-
* or dismissed it). Clearing is what lets a later agent request raise a new
|
|
2370
|
-
* dialog instead of being swallowed by the dedupe guard.
|
|
2371
|
-
* @param {object} [body]
|
|
2372
|
-
* @returns {Promise<{cleared: boolean}>}
|
|
2373
|
-
*/
|
|
2374
|
-
async reviewPendingClear(body) {
|
|
2375
|
-
const id = optionalString(body?.id);
|
|
2376
|
-
if (id !== undefined && this.#reviewRequest && this.#reviewRequest.id !== id) {
|
|
2377
|
-
return { cleared: false };
|
|
2378
|
-
}
|
|
2379
|
-
const had = this.#reviewRequest !== null;
|
|
2380
|
-
this.#reviewRequest = null;
|
|
2381
|
-
return { cleared: had };
|
|
2382
|
-
}
|
|
2383
|
-
|
|
2384
|
-
/* ---------------- DevDock npm module (read-only) ---------------- */
|
|
2385
|
-
|
|
2386
|
-
/**
|
|
2387
|
-
* `GET /npm/accounts` — npm accounts without their tokens.
|
|
2388
|
-
* @returns {Promise<object>}
|
|
2389
|
-
*/
|
|
2390
|
-
async npmAccounts() {
|
|
2391
|
-
return this.#store.npmAccounts();
|
|
2392
|
-
}
|
|
2393
|
-
|
|
2394
|
-
/**
|
|
2395
|
-
* `POST /npm/account` — verify a token against the registry, then store it.
|
|
2396
|
-
*
|
|
2397
|
-
* The token is checked BEFORE it is saved: storing an unverified token is
|
|
2398
|
-
* how a settings page ends up showing an account that cannot do anything.
|
|
2399
|
-
*
|
|
2400
|
-
* @param {object} body `{ token }`
|
|
2401
|
-
* @returns {Promise<object>}
|
|
2402
|
-
*/
|
|
2403
|
-
async npmAccountAdd(body) {
|
|
2404
|
-
const token = requireString(body, 'token', 'npm 令牌').trim();
|
|
2405
|
-
const who = await npmWhoami({ token });
|
|
2406
|
-
const saved = await this.#store.saveNpmAccount({ login: who.login, token });
|
|
2407
|
-
return saved;
|
|
2408
|
-
}
|
|
2409
|
-
|
|
2410
|
-
/**
|
|
2411
|
-
* `POST /npm/account/remove` — forget one npm account.
|
|
2412
|
-
* @param {object} body `{ id }`
|
|
2413
|
-
* @returns {Promise<{removed: boolean}>}
|
|
2414
|
-
*/
|
|
2415
|
-
async npmAccountRemove(body) {
|
|
2416
|
-
const id = requireString(body, 'id', '账号 id');
|
|
2417
|
-
const removed = await this.#store.deleteNpmAccount(id);
|
|
2418
|
-
if (!removed) throw httpError(404, 'NOT_FOUND', '找不到这个 npm 账号,可能已被移除。');
|
|
2419
|
-
return { removed: true };
|
|
2420
|
-
}
|
|
2421
|
-
|
|
2422
|
-
/**
|
|
2423
|
-
* `POST /npm/account/active` — switch the current npm account.
|
|
2424
|
-
* @param {object} body `{ id }`
|
|
2425
|
-
* @returns {Promise<{activeId: string}>}
|
|
2426
|
-
*/
|
|
2427
|
-
async npmAccountActive(body) {
|
|
2428
|
-
const id = requireString(body, 'id', '账号 id');
|
|
2429
|
-
const ok = await this.#store.setActiveNpmAccount(id);
|
|
2430
|
-
if (!ok) throw httpError(404, 'NOT_FOUND', '找不到这个 npm 账号。');
|
|
2431
|
-
return { activeId: id };
|
|
2432
|
-
}
|
|
2433
|
-
|
|
2434
|
-
/** 当前 npm 账号,缺失时给出可执行的提示而不是空结果。 */
|
|
2435
|
-
async #requireNpmAccount() {
|
|
2436
|
-
const account = await this.#store.activeNpmAccount();
|
|
2437
|
-
if (!account) {
|
|
2438
|
-
throw httpError(401, 'NO_ACCOUNT', '还没有登录 npm。请在设置 › npm 中添加一个 Granular Access Token。');
|
|
2439
|
-
}
|
|
2440
|
-
return account;
|
|
2441
|
-
}
|
|
2442
|
-
|
|
2443
|
-
/**
|
|
2444
|
-
* `GET /npm/packages` — packages the current account maintains.
|
|
2445
|
-
* @param {object} query
|
|
2446
|
-
* @returns {Promise<object>}
|
|
2447
|
-
*/
|
|
2448
|
-
async npmPackages(query) {
|
|
2449
|
-
const account = await this.#requireNpmAccount();
|
|
2450
|
-
const result = await npmSearchByMaintainer({
|
|
2451
|
-
token: account.token,
|
|
2452
|
-
login: account.login,
|
|
2453
|
-
size: Number.isFinite(query && query.size) ? Number(query.size) : 20,
|
|
2454
|
-
from: Number.isFinite(query && query.from) ? Number(query.from) : 0,
|
|
2455
|
-
});
|
|
2456
|
-
await this.#store.touchNpmAccount(account.id);
|
|
2457
|
-
return {
|
|
2458
|
-
login: account.login,
|
|
2459
|
-
items: result.items,
|
|
2460
|
-
total: result.total,
|
|
2461
|
-
};
|
|
2462
|
-
}
|
|
2463
|
-
|
|
2464
|
-
/* ---------------- npm CLI: 初始化 / 打包 / 发布 ---------------- */
|
|
2465
|
-
|
|
2466
|
-
/** @returns {NpmRunner} 复用同一个执行器(二进制与超时只解析一次)。 */
|
|
2467
|
-
#npmRunner() {
|
|
2468
|
-
if (!this.#npmRunnerCache) this.#npmRunnerCache = new NpmRunner();
|
|
2469
|
-
return this.#npmRunnerCache;
|
|
2470
|
-
}
|
|
2471
|
-
|
|
2472
|
-
#npmRunnerCache = null;
|
|
2473
|
-
|
|
2474
|
-
/**
|
|
2475
|
-
* `POST /npm/init` — 给一个还没有 package.json 的目录生成一份。
|
|
2476
|
-
*
|
|
2477
|
-
* 只在文件不存在时写,绝不覆盖:一个已有 package.json 的目录被意外
|
|
2478
|
-
* 重置,代价远大于省掉一次手动创建。
|
|
2479
|
-
*
|
|
2480
|
-
* @param {{path?: string, name?: string, version?: string}} body
|
|
2481
|
-
* @returns {Promise<object>}
|
|
2482
|
-
*/
|
|
2483
|
-
async npmInit(body) {
|
|
2484
|
-
const dir = typeof body.path === 'string' && body.path.trim() !== ''
|
|
2485
|
-
? body.path.trim()
|
|
2486
|
-
: process.cwd();
|
|
2487
|
-
const file = path.join(dir, 'package.json');
|
|
2488
|
-
|
|
2489
|
-
try {
|
|
2490
|
-
await readFile(file, 'utf8');
|
|
2491
|
-
throw httpError(409, 'BAD_REQUEST', '这个目录已经有 package.json 了,不会覆盖它。');
|
|
2492
|
-
} catch (error) {
|
|
2493
|
-
if (error && error.code !== 'ENOENT' && !error.status) throw error;
|
|
2494
|
-
if (error && error.status) throw error;
|
|
2495
|
-
}
|
|
2496
|
-
|
|
2497
|
-
// 默认包名取目录名:npm 只接受小写与有限字符,先规范化再判断。
|
|
2498
|
-
const fallback = path.basename(dir).toLowerCase().replace(/[^a-z0-9._~-]+/g, '-').replace(/^-+|-+$/g, '');
|
|
2499
|
-
const name = typeof body.name === 'string' && body.name.trim() !== ''
|
|
2500
|
-
? body.name.trim()
|
|
2501
|
-
: (fallback === '' ? 'my-package' : fallback);
|
|
2502
|
-
const version = typeof body.version === 'string' && body.version.trim() !== ''
|
|
2503
|
-
? body.version.trim()
|
|
2504
|
-
: '0.1.0';
|
|
2505
|
-
|
|
2506
|
-
const doc = {
|
|
2507
|
-
name,
|
|
2508
|
-
version,
|
|
2509
|
-
description: '',
|
|
2510
|
-
main: 'index.js',
|
|
2511
|
-
scripts: { test: 'echo "no test specified" && exit 1' },
|
|
2512
|
-
keywords: [],
|
|
2513
|
-
license: 'MIT',
|
|
2514
|
-
files: ['index.js'],
|
|
2515
|
-
};
|
|
2516
|
-
|
|
2517
|
-
try {
|
|
2518
|
-
await writeFile(file, JSON.stringify(doc, null, 2) + '\n', 'utf8');
|
|
2519
|
-
} catch (error) {
|
|
2520
|
-
throw httpError(500, 'INTERNAL', `无法写入 package.json:${error.message}`);
|
|
2521
|
-
}
|
|
2522
|
-
|
|
2523
|
-
return { path: file, created: true, name, version };
|
|
2524
|
-
}
|
|
2525
|
-
|
|
2526
|
-
/**
|
|
2527
|
-
* `GET /npm/pack` — 预演打包:npm 会收进哪些文件、多大。
|
|
2528
|
-
*
|
|
2529
|
-
* 只跑 `--dry-run`,不落任何文件。这是「打包审查」的数据来源。
|
|
2530
|
-
*
|
|
2531
|
-
* @param {{path?: string}} query
|
|
2532
|
-
* @returns {Promise<object>}
|
|
2533
|
-
*/
|
|
2534
|
-
async npmPackInspect(query) {
|
|
2535
|
-
const dir = typeof query.path === 'string' && query.path.trim() !== ''
|
|
2536
|
-
? query.path.trim()
|
|
2537
|
-
: process.cwd();
|
|
2538
|
-
const runner = this.#npmRunner();
|
|
2539
|
-
const result = await runner.run(['pack', '--dry-run', '--json'], { cwd: dir });
|
|
2540
|
-
const packed = mapPackResult(parsePackJson(result.stdout));
|
|
2541
|
-
return { ...packed, dryRun: true };
|
|
2542
|
-
}
|
|
2543
|
-
|
|
2544
|
-
/**
|
|
2545
|
-
* `POST /npm/pack` — 真正生成 .tgz。
|
|
2546
|
-
*
|
|
2547
|
-
* @param {{path?: string}} body
|
|
2548
|
-
* @returns {Promise<object>}
|
|
2549
|
-
*/
|
|
2550
|
-
async npmPack(body) {
|
|
2551
|
-
const dir = typeof body.path === 'string' && body.path.trim() !== ''
|
|
2552
|
-
? body.path.trim()
|
|
2553
|
-
: process.cwd();
|
|
2554
|
-
const runner = this.#npmRunner();
|
|
2555
|
-
const result = await runner.run(['pack', '--json'], { cwd: dir });
|
|
2556
|
-
const packed = mapPackResult(parsePackJson(result.stdout));
|
|
2557
|
-
return { ...packed, dryRun: false, path: path.join(dir, packed.filename) };
|
|
2558
|
-
}
|
|
2559
|
-
|
|
2560
|
-
/**
|
|
2561
|
-
* `POST /npm/review/run` — 发布前审查。
|
|
2562
|
-
*
|
|
2563
|
-
* 与 GitHub 的推送前审查共用预设、模型选择与结果结构;差别只在
|
|
2564
|
-
* 审查对象——这里是「npm pack 会打进去的文件」,而不是 git diff。
|
|
2565
|
-
*
|
|
2566
|
-
* @param {object} body `{ path, presetIds, customPrompt, provider, model,
|
|
2567
|
-
* reasoningEffort, maxFiles }`
|
|
2568
|
-
* @returns {Promise<object>}
|
|
2569
|
-
*/
|
|
2570
|
-
async npmPublishReview(body) {
|
|
2571
|
-
const dir = typeof body.path === 'string' && body.path.trim() !== ''
|
|
2572
|
-
? body.path.trim()
|
|
2573
|
-
: process.cwd();
|
|
2574
|
-
|
|
2575
|
-
// 1. npm 会打进去哪些文件——与打包面板同一数据源,结果必然一致。
|
|
2576
|
-
const runner = this.#npmRunner();
|
|
2577
|
-
const packed = mapPackResult(parsePackJson(
|
|
2578
|
-
(await runner.run(['pack', '--dry-run', '--json'], { cwd: dir })).stdout,
|
|
2579
|
-
));
|
|
2580
|
-
|
|
2581
|
-
// 2. 读这些文件的文本内容。二进制与超大文件跳过并记下原因。
|
|
2582
|
-
const maxFiles = Number.isFinite(body.maxFiles) ? Number(body.maxFiles) : 80;
|
|
2583
|
-
const maxBytes = MAX_FILE_BYTES;
|
|
2584
|
-
const files = [];
|
|
2585
|
-
const chunks = [];
|
|
2586
|
-
let truncated = false;
|
|
2587
|
-
|
|
2588
|
-
for (const row of packed.files) {
|
|
2589
|
-
if (chunks.length >= maxFiles) { truncated = true; break; }
|
|
2590
|
-
const rel = row.path.replace(/\/$/, '');
|
|
2591
|
-
if (/(^|\/)(node_modules|\.git)\//.test(rel)) continue;
|
|
2592
|
-
if (row.size > maxBytes) {
|
|
2593
|
-
files.push({ path: rel, skipped: '文件过大' });
|
|
2594
|
-
truncated = true;
|
|
2595
|
-
continue;
|
|
2596
|
-
}
|
|
2597
|
-
let text;
|
|
2598
|
-
try {
|
|
2599
|
-
text = await readFile(path.join(dir, rel), 'utf8');
|
|
2600
|
-
} catch {
|
|
2601
|
-
files.push({ path: rel, skipped: '无法读取' });
|
|
2602
|
-
continue;
|
|
2603
|
-
}
|
|
2604
|
-
if (text.includes('\u0000')) {
|
|
2605
|
-
files.push({ path: rel, skipped: '二进制文件' });
|
|
2606
|
-
continue;
|
|
2607
|
-
}
|
|
2608
|
-
files.push({ path: rel });
|
|
2609
|
-
chunks.push({ path: rel, text });
|
|
2610
|
-
}
|
|
2611
|
-
|
|
2612
|
-
// 3. 规则扫描:永远执行,免费且确定。
|
|
2613
|
-
const ruleFindings = [];
|
|
2614
|
-
for (const chunk of chunks) {
|
|
2615
|
-
ruleFindings.push(...scanSecrets(chunk.text, { file: chunk.path }));
|
|
2616
|
-
}
|
|
2617
|
-
|
|
2618
|
-
// 4. 包完整性:这些不是「代码问题」,但发布前必须看见。
|
|
2619
|
-
if (packed.totalFiles === 0) {
|
|
2620
|
-
ruleFindings.push(normalizeFinding({
|
|
2621
|
-
severity: 'blocker',
|
|
2622
|
-
title: '包内没有任何文件',
|
|
2623
|
-
detail: 'npm pack 没有收集到文件,发布出去会是一个空包。检查 files 字段与 .npmignore。',
|
|
2624
|
-
file: 'package.json',
|
|
2625
|
-
}));
|
|
2626
|
-
}
|
|
2627
|
-
|
|
2628
|
-
if (!packed.files.some((row) => /(^|\/)readme(\.md|\.txt)?$/i.test(row.path))) {
|
|
2629
|
-
ruleFindings.push(normalizeFinding({
|
|
2630
|
-
severity: 'medium',
|
|
2631
|
-
title: '包里没有 README',
|
|
2632
|
-
detail: 'npm 页面会没有任何说明文字,用户看到的是一个空白页。',
|
|
2633
|
-
file: 'README.md',
|
|
2634
|
-
}));
|
|
2635
|
-
}
|
|
2636
|
-
|
|
2637
|
-
const sizeLimit = 10 * 1024 * 1024;
|
|
2638
|
-
if (packed.size !== null && packed.size > sizeLimit) {
|
|
2639
|
-
ruleFindings.push(normalizeFinding({
|
|
2640
|
-
severity: 'medium',
|
|
2641
|
-
title: '包体积偏大',
|
|
2642
|
-
detail: `压缩后 ${Math.round(packed.size / 1024)} KB。检查是否误把构建产物或测试数据打进来了。`,
|
|
2643
|
-
file: 'package.json',
|
|
2644
|
-
}));
|
|
2645
|
-
}
|
|
2646
|
-
|
|
2647
|
-
// 5. 模型审查:与 reviewRun 同样的解析方式与调用形状。
|
|
2648
|
-
const presetIds = Array.isArray(body.presetIds)
|
|
2649
|
-
? body.presetIds.filter((id) => typeof id === 'string' && id !== '')
|
|
2650
|
-
: [];
|
|
2651
|
-
const stored = await this.#store.reviewPresets();
|
|
2652
|
-
const chosen = [
|
|
2653
|
-
...BUILTIN_PRESETS.filter((preset) => presetIds.includes(preset.id)),
|
|
2654
|
-
...stored.filter((preset) => presetIds.includes(preset.id)),
|
|
2655
|
-
];
|
|
2656
|
-
const customPrompt = optionalString(body.customPrompt) ?? '';
|
|
2657
|
-
|
|
2658
|
-
const llm = this.#llm();
|
|
2659
|
-
let provider = optionalString(body.provider);
|
|
2660
|
-
let model = optionalString(body.model);
|
|
2661
|
-
if (llm && (!provider || !model)) {
|
|
2662
|
-
try {
|
|
2663
|
-
const fallback = await this.reviewModels();
|
|
2664
|
-
if (fallback.default) {
|
|
2665
|
-
provider = provider ?? fallback.default.provider;
|
|
2666
|
-
model = model ?? fallback.default.model;
|
|
2667
|
-
}
|
|
2668
|
-
} catch { /* 保留调用方给的值 */ }
|
|
2669
|
-
}
|
|
2670
|
-
|
|
2671
|
-
const instructions = [
|
|
2672
|
-
...chosen.map((preset) => `## ${preset.title}\n${preset.prompt}`),
|
|
2673
|
-
...(customPrompt ? [`## 用户补充要求\n${customPrompt}`] : []),
|
|
2674
|
-
].join('\n\n');
|
|
2675
|
-
|
|
2676
|
-
/* 明确告诉模型它看的是什么、不是什么。少了这段,模型会把
|
|
2677
|
-
* 「没有出现在包里的文件」误报成「项目缺少文件」。 */
|
|
2678
|
-
const promptParts = [];
|
|
2679
|
-
if (instructions !== '') promptParts.push(instructions);
|
|
2680
|
-
promptParts.push('## 审查范围');
|
|
2681
|
-
promptParts.push('本次审查的是 npm 发布包的内容:以下文件就是 npm pack 会打进去的全部文件,'
|
|
2682
|
-
+ '不代表项目里只有这些文件。未列出的文件不会随包发布,不要据此推断项目缺少文件。');
|
|
2683
|
-
promptParts.push(`## 包内文件(${files.length} 个,压缩后 ${packed.size ?? 0} 字节)`);
|
|
2684
|
-
promptParts.push(files.map((file) => `- ${file.path}${file.skipped ? `(未送审:${file.skipped})` : ''}`).join('\n'));
|
|
2685
|
-
promptParts.push('## 内容');
|
|
2686
|
-
promptParts.push(chunks.length === 0
|
|
2687
|
-
? '(没有可审查的文本内容)'
|
|
2688
|
-
: chunks.map((chunk) => `### ${chunk.path}\n\`\`\`\n${chunk.text}\n\`\`\``).join('\n\n'));
|
|
2689
|
-
|
|
2690
|
-
if (truncated) {
|
|
2691
|
-
promptParts.push('严重提示:因体积或数量限制,本次内容并不完整。只针对你实际看到的内容报告问题。');
|
|
2692
|
-
}
|
|
2693
|
-
|
|
2694
|
-
let modelFindings = [];
|
|
2695
|
-
let summary = '';
|
|
2696
|
-
let usage;
|
|
2697
|
-
let degraded = false;
|
|
2698
|
-
|
|
2699
|
-
if (!llm) {
|
|
2700
|
-
degraded = true;
|
|
2701
|
-
summary = '宿主未提供 llm 服务,本次只执行了规则检查(敏感信息扫描)。';
|
|
2702
|
-
} else if (!provider || !model) {
|
|
2703
|
-
degraded = true;
|
|
2704
|
-
summary = '未找到可用的模型,本次只执行了规则检查(敏感信息扫描)。';
|
|
2705
|
-
} else if (chunks.length === 0) {
|
|
2706
|
-
summary = '包里没有可审查的文本内容。';
|
|
2707
|
-
} else {
|
|
2708
|
-
try {
|
|
2709
|
-
const result = await runModelReview(llm, {
|
|
2710
|
-
provider,
|
|
2711
|
-
model,
|
|
2712
|
-
reasoningEffort: optionalString(body.reasoningEffort),
|
|
2713
|
-
prompt: promptParts.join('\n\n'),
|
|
2714
|
-
});
|
|
2715
|
-
modelFindings = result.findings.map(normalizeFinding);
|
|
2716
|
-
summary = result.summary;
|
|
2717
|
-
usage = result.usage;
|
|
2718
|
-
} catch (error) {
|
|
2719
|
-
degraded = true;
|
|
2720
|
-
summary = `模型审查失败(${String(error && error.message ? error.message : error)}),本次只执行了规则检查。`;
|
|
2721
|
-
}
|
|
2722
|
-
}
|
|
2723
|
-
|
|
2724
|
-
const findings = sortFindings([...ruleFindings, ...modelFindings]);
|
|
2725
|
-
if (summary === '') {
|
|
2726
|
-
summary = findings.length === 0 ? '未发现明显问题。' : `共发现 ${findings.length} 处需要关注的问题。`;
|
|
2727
|
-
}
|
|
2728
|
-
|
|
2729
|
-
return {
|
|
2730
|
-
reviewId: `npmreview_${Date.now().toString(36)}`,
|
|
2731
|
-
scope: 'package',
|
|
2732
|
-
model: provider && model
|
|
2733
|
-
? { provider, model, label: `${provider} / ${model}` }
|
|
2734
|
-
: null,
|
|
2735
|
-
effort: optionalString(body.reasoningEffort) ?? null,
|
|
2736
|
-
files,
|
|
2737
|
-
findings,
|
|
2738
|
-
summary,
|
|
2739
|
-
usage,
|
|
2740
|
-
degraded,
|
|
2741
|
-
truncated,
|
|
2742
|
-
pack: {
|
|
2743
|
-
totalFiles: packed.totalFiles,
|
|
2744
|
-
size: packed.size,
|
|
2745
|
-
unpackedSize: packed.unpackedSize,
|
|
2746
|
-
},
|
|
2747
|
-
};
|
|
2748
|
-
}
|
|
2749
|
-
|
|
2750
|
-
/**
|
|
2751
|
-
* `POST /npm/publish` — 发布到 npm。
|
|
2752
|
-
*
|
|
2753
|
-
* 需要 2FA 的账号必须带 otp;没有 otp 时 npm 的报错会被原样翻译成一句
|
|
2754
|
-
* 可执行的提示,而不是让用户对着 EOTP 发呆。
|
|
2755
|
-
*
|
|
2756
|
-
* @param {{path?: string, otp?: string, tag?: string}} body
|
|
2757
|
-
* @returns {Promise<object>}
|
|
2758
|
-
*/
|
|
2759
|
-
async npmPublish(body) {
|
|
2760
|
-
const account = await this.#store.activeNpmAccount();
|
|
2761
|
-
if (!account) {
|
|
2762
|
-
throw httpError(401, 'NO_ACCOUNT', '还没有登录 npm,请先在设置 › npm 添加令牌。');
|
|
2763
|
-
}
|
|
2764
|
-
const dir = typeof body.path === 'string' && body.path.trim() !== ''
|
|
2765
|
-
? body.path.trim()
|
|
2766
|
-
: process.cwd();
|
|
2767
|
-
|
|
2768
|
-
const args = ['publish', '--json'];
|
|
2769
|
-
// prepublishOnly 里的 `npm test` 在 monorepo workspace 环境下会与工作区根
|
|
2770
|
-
// 的 test 脚本互相缠绕(根目录 test = npm --workspace dsh-push test,而
|
|
2771
|
-
// dsh-push 的 prepublishOnly 又是 npm test),导致发布前钩子递归失败。
|
|
2772
|
-
// 发布前的测试已经由项目审查(/review/project)承担,这里跳过脚本。
|
|
2773
|
-
args.push('--ignore-scripts');
|
|
2774
|
-
// 防御性校验:--tag 是 dist-tag 名,只允许 npm 认可的字符;
|
|
2775
|
-
// --otp 是 6-8 位数字。任何越界字符直接拒绝,不进入子进程 argv。
|
|
2776
|
-
const tag = typeof body.tag === 'string' ? body.tag.trim() : '';
|
|
2777
|
-
if (tag !== '') {
|
|
2778
|
-
if (!/^[a-zA-Z0-9._@-]+$/.test(tag) || tag.length > 64) {
|
|
2779
|
-
throw httpError(400, 'BAD_REQUEST', '发布标签(tag)含非法字符,只能是字母、数字、点、下划线、连字符。');
|
|
2780
|
-
}
|
|
2781
|
-
args.push('--tag', tag);
|
|
2782
|
-
}
|
|
2783
|
-
const otp = typeof body.otp === 'string' ? body.otp.trim() : '';
|
|
2784
|
-
if (otp !== '') {
|
|
2785
|
-
if (!/^\d{6,8}$/.test(otp)) {
|
|
2786
|
-
throw httpError(400, 'BAD_REQUEST', '验证码(otp)必须是 6 到 8 位数字。');
|
|
2787
|
-
}
|
|
2788
|
-
args.push('--otp', otp);
|
|
2789
|
-
}
|
|
2790
|
-
|
|
2791
|
-
const runner = this.#npmRunner();
|
|
2792
|
-
try {
|
|
2793
|
-
const result = await runner.run(args, {
|
|
2794
|
-
cwd: dir,
|
|
2795
|
-
env: npmAuthEnv(account.token),
|
|
2796
|
-
});
|
|
2797
|
-
// npm publish 的输出不是 pack 的 JSON 结构,别用 parsePackJson 解析。
|
|
2798
|
-
// 从 package.json 读回真实的 name/version,这是发布出去的确切值。
|
|
2799
|
-
let name = '';
|
|
2800
|
-
let version = '';
|
|
2801
|
-
try {
|
|
2802
|
-
const doc = JSON.parse(await readFile(path.join(dir, 'package.json'), 'utf8'));
|
|
2803
|
-
name = doc.name ?? '';
|
|
2804
|
-
version = doc.version ?? '';
|
|
2805
|
-
} catch { /* 读不到就用空值 */ }
|
|
2806
|
-
await this.#store.touchNpmAccount(account.id);
|
|
2807
|
-
return { published: true, name, version };
|
|
2808
|
-
} catch (error) {
|
|
2809
|
-
const text = `${error.stderr || ''} ${error.message || ''}`;
|
|
2810
|
-
if (/EOTP|one-time password|two-factor/i.test(text)) {
|
|
2811
|
-
throw httpError(401, 'UNAUTHORIZED', '这次发布需要一次性验证码(2FA):请在发布对话框里填入 6 位验证码后重试。');
|
|
2812
|
-
}
|
|
2813
|
-
if (/E403|403 Forbidden|cannot publish over/i.test(text)) {
|
|
2814
|
-
throw httpError(403, 'FORBIDDEN', error.message);
|
|
2815
|
-
}
|
|
2816
|
-
// 带上完整 stderr 尾部,否则 prepublishOnly 里的测试失败原因被截断,
|
|
2817
|
-
// 只能看到「npm test」三个字,无从定位。
|
|
2818
|
-
const tail = String(error.stderr || error.stdout || '')
|
|
2819
|
-
.split('\n').filter((line) => line.trim() !== '').slice(-12).join('\n');
|
|
2820
|
-
throw httpError(500, 'INTERNAL', error.message + (tail ? '\n---\n' + tail : ''));
|
|
2821
|
-
}
|
|
2822
|
-
}
|
|
2823
|
-
|
|
2824
|
-
/**
|
|
2825
|
-
* `GET /npm/search` — 按关键词搜索 npm 上的包。
|
|
2826
|
-
*
|
|
2827
|
-
* 公开数据,不要求登录;有账号时带上令牌,私有包才搜得到。
|
|
2828
|
-
*
|
|
2829
|
-
* @param {{q?: string, size?: number}} query
|
|
2830
|
-
* @returns {Promise<object>}
|
|
2831
|
-
*/
|
|
2832
|
-
async npmSearch(query) {
|
|
2833
|
-
const text = typeof query.q === 'string' ? query.q.trim() : '';
|
|
2834
|
-
if (text === '') throw httpError(400, 'BAD_REQUEST', '请输入要搜索的包名或关键词。');
|
|
2835
|
-
const account = await this.#store.activeNpmAccount();
|
|
2836
|
-
const result = await npmSearchText({
|
|
2837
|
-
text,
|
|
2838
|
-
size: Number.isFinite(query.size) ? Number(query.size) : 20,
|
|
2839
|
-
token: account ? account.token : undefined,
|
|
2840
|
-
});
|
|
2841
|
-
return { query: text, items: result.items, total: result.total };
|
|
2842
|
-
}
|
|
2843
|
-
|
|
2844
|
-
/**
|
|
2845
|
-
* `GET /npm/preflight` — 发布前自检。
|
|
2846
|
-
*
|
|
2847
|
-
* 把「发了才发现包名被占 / 版本重复 / 忘了 README」这几类错误提前到
|
|
2848
|
-
* 本地就能发现。检查分三级:fail 会直接导致发布失败,warn 多半是遗漏,
|
|
2849
|
-
* info 只是提示。
|
|
2850
|
-
*
|
|
2851
|
-
* 只读本地 package.json 与 registry,不写任何东西。
|
|
2852
|
-
*
|
|
2853
|
-
* @param {{path?: string}} options
|
|
2854
|
-
* @returns {Promise<object>}
|
|
2855
|
-
*/
|
|
2856
|
-
async npmPreflight(options) {
|
|
2857
|
-
const dir = typeof options.path === 'string' && options.path.trim() !== ''
|
|
2858
|
-
? options.path.trim()
|
|
2859
|
-
: process.cwd();
|
|
2860
|
-
const file = path.join(dir, 'package.json');
|
|
2861
|
-
let raw;
|
|
2862
|
-
try {
|
|
2863
|
-
raw = await readFile(file, 'utf8');
|
|
2864
|
-
} catch {
|
|
2865
|
-
throw httpError(404, 'NOT_FOUND', `这个目录下没有 package.json:${dir}`);
|
|
2866
|
-
}
|
|
2867
|
-
let doc;
|
|
2868
|
-
try { doc = JSON.parse(raw); } catch {
|
|
2869
|
-
throw httpError(400, 'BAD_REQUEST', 'package.json 不是合法 JSON。');
|
|
2870
|
-
}
|
|
2871
|
-
|
|
2872
|
-
const checks = [];
|
|
2873
|
-
const add = (id, level, message, hint) => checks.push({ id, level, message, hint: hint || '' });
|
|
2874
|
-
const exists = async (rel) => {
|
|
2875
|
-
try { await readFile(path.join(dir, rel)); return true; } catch { return false; }
|
|
2876
|
-
};
|
|
2877
|
-
|
|
2878
|
-
const name = typeof doc.name === 'string' ? doc.name.trim() : '';
|
|
2879
|
-
const version = typeof doc.version === 'string' ? doc.version.trim() : '';
|
|
2880
|
-
|
|
2881
|
-
if (name === '') add('name', 'fail', '缺少 name 字段', 'npm 用 name 作为包的唯一标识');
|
|
2882
|
-
else if (!/^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(name)) {
|
|
2883
|
-
add('name', 'fail', 'name 不是合法的 npm 包名', '只能是小写字母、数字、- . _ ~;scope 用 @scope/name');
|
|
2884
|
-
} else {
|
|
2885
|
-
add('name', 'pass', 'name 格式合法', name);
|
|
2886
|
-
}
|
|
2887
|
-
|
|
2888
|
-
if (version === '') add('version', 'fail', '缺少 version 字段', '发布必须带版本号');
|
|
2889
|
-
else if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) {
|
|
2890
|
-
add('version', 'fail', 'version 不是合法 semver', version);
|
|
2891
|
-
} else {
|
|
2892
|
-
add('version', 'pass', 'version 格式合法', version);
|
|
2893
|
-
}
|
|
2894
|
-
|
|
2895
|
-
// registry 占用:名字被占用不一定是问题,版本重复一定是。
|
|
2896
|
-
if (name !== '') {
|
|
2897
|
-
const account = await this.#store.activeNpmAccount();
|
|
2898
|
-
const status = await npmPackageStatus({ name, token: account ? account.token : undefined });
|
|
2899
|
-
if (status.error) {
|
|
2900
|
-
add('registry', 'warn', '无法查询 registry', status.error);
|
|
2901
|
-
} else if (!status.exists) {
|
|
2902
|
-
add('registry', 'pass', '包名未被占用', name);
|
|
2903
|
-
} else {
|
|
2904
|
-
add('registry', 'info', 'npm 上已存在同名包',
|
|
2905
|
-
'如果这是你自己的包就正常;否则发布会被拒绝。latest 为 ' + (status.latest || '—'));
|
|
2906
|
-
if (version !== '' && status.versions.includes(version)) {
|
|
2907
|
-
add('version-taken', 'fail', '这个版本已经发布过',
|
|
2908
|
-
version + ' 已存在,请提升版本号后再发布');
|
|
2909
|
-
}
|
|
2910
|
-
}
|
|
2911
|
-
}
|
|
2912
|
-
|
|
2913
|
-
// 常见遗漏:README / LICENSE / files。
|
|
2914
|
-
if (await exists('README.md')) add('readme', 'pass', 'README.md 存在', '');
|
|
2915
|
-
else add('readme', 'warn', '缺少 README.md', 'npm 页面会没有说明');
|
|
2916
|
-
|
|
2917
|
-
const licenseFile = (await exists('LICENSE')) || (await exists('LICENSE.md'));
|
|
2918
|
-
if (licenseFile) add('license', 'pass', '许可证文件存在', '');
|
|
2919
|
-
else if (typeof doc.license === 'string' && doc.license !== '') {
|
|
2920
|
-
add('license', 'pass', 'package.json 声明了 license', doc.license);
|
|
2921
|
-
} else {
|
|
2922
|
-
add('license', 'warn', '没有许可证文件,也没声明 license', '默认发布出去的包是不可自由使用的');
|
|
2923
|
-
}
|
|
2924
|
-
|
|
2925
|
-
const files = Array.isArray(doc.files) ? doc.files : null;
|
|
2926
|
-
if (files) {
|
|
2927
|
-
add('files', 'pass', 'package.json 声明了 files', files.length + ' 项');
|
|
2928
|
-
} else {
|
|
2929
|
-
add('files', 'warn', '没有声明 files 字段', '默认会把目录下几乎所有文件都发布出去');
|
|
2930
|
-
}
|
|
2931
|
-
|
|
2932
|
-
// 入口文件必须真实存在,否则装了也 require 不到。
|
|
2933
|
-
if (typeof doc.main === 'string' && doc.main !== '') {
|
|
2934
|
-
if (await exists(doc.main)) add('main', 'pass', 'main 指向的文件存在', doc.main);
|
|
2935
|
-
else add('main', 'fail', 'main 指向的文件不存在', doc.main);
|
|
2936
|
-
}
|
|
2937
|
-
|
|
2938
|
-
if (doc.private === true) {
|
|
2939
|
-
add('private', 'fail', 'package.json 标了 private: true', 'private 的包无法发布,先去掉这个字段');
|
|
2940
|
-
}
|
|
2941
|
-
|
|
2942
|
-
const counts = {
|
|
2943
|
-
fail: checks.filter((row) => row.level === 'fail').length,
|
|
2944
|
-
warn: checks.filter((row) => row.level === 'warn').length,
|
|
2945
|
-
pass: checks.filter((row) => row.level === 'pass').length,
|
|
2946
|
-
info: checks.filter((row) => row.level === 'info').length,
|
|
2947
|
-
};
|
|
2948
|
-
|
|
2949
|
-
return {
|
|
2950
|
-
path: file,
|
|
2951
|
-
name,
|
|
2952
|
-
version,
|
|
2953
|
-
checks,
|
|
2954
|
-
counts,
|
|
2955
|
-
// 只有 fail 会阻止发布;warn 值得看一眼但不必拦。
|
|
2956
|
-
publishable: counts.fail === 0,
|
|
2957
|
-
};
|
|
2958
|
-
}
|
|
2959
|
-
|
|
2960
|
-
/**
|
|
2961
|
-
* `GET /npm/deps` — 工作区 package.json 里的依赖 /**
|
|
2962
|
-
* `GET /npm/deps` — 工作区 package.json 里的依赖,逐个比对 npm 上的最新版。
|
|
2963
|
-
*
|
|
2964
|
-
* 这是本插件少有的「不需要跳去别处」的 npm 能力:它读的是本地文件,
|
|
2965
|
-
* 只把版本号拿去问 registry,最后在面板里直接给出「有没有更新」。
|
|
2966
|
-
*
|
|
2967
|
-
* 之所以并发受限,是因为一个正常项目有几十个依赖,逐个串行会慢到没人
|
|
2968
|
-
* 愿意等;但全部并发又会触发 registry 的速率限制。
|
|
2969
|
-
*
|
|
2970
|
-
* @param {{path?: string, token?: string}} options
|
|
2971
|
-
* @returns {Promise<object>}
|
|
2972
|
-
*/
|
|
2973
|
-
async npmProjectDeps(options) {
|
|
2974
|
-
const dir = typeof options.path === 'string' && options.path.trim() !== ''
|
|
2975
|
-
? options.path.trim()
|
|
2976
|
-
: process.cwd();
|
|
2977
|
-
const file = path.join(dir, 'package.json');
|
|
2978
|
-
let raw;
|
|
2979
|
-
try {
|
|
2980
|
-
raw = await readFile(file, 'utf8');
|
|
2981
|
-
} catch {
|
|
2982
|
-
throw httpError(404, 'NOT_FOUND', `这个目录下没有 package.json:${dir}`);
|
|
2983
|
-
}
|
|
2984
|
-
let doc;
|
|
2985
|
-
try {
|
|
2986
|
-
doc = JSON.parse(raw);
|
|
2987
|
-
} catch {
|
|
2988
|
-
throw httpError(400, 'BAD_REQUEST', 'package.json 不是合法 JSON,无法解析。');
|
|
2989
|
-
}
|
|
2990
|
-
|
|
2991
|
-
const groups = [
|
|
2992
|
-
['dependencies', doc.dependencies],
|
|
2993
|
-
['devDependencies', doc.devDependencies],
|
|
2994
|
-
];
|
|
2995
|
-
const rows = [];
|
|
2996
|
-
for (const [group, table] of groups) {
|
|
2997
|
-
if (!table || typeof table !== 'object') continue;
|
|
2998
|
-
for (const [name, range] of Object.entries(table)) {
|
|
2999
|
-
if (typeof range !== 'string') continue;
|
|
3000
|
-
rows.push({ name, range, group });
|
|
3001
|
-
}
|
|
3002
|
-
}
|
|
3003
|
-
|
|
3004
|
-
const account = await this.#store.activeNpmAccount();
|
|
3005
|
-
const token = account ? account.token : undefined;
|
|
3006
|
-
|
|
3007
|
-
// 限并发 6:既不慢到不可用,也不至于把注册表打到限流。
|
|
3008
|
-
const CONCURRENCY = 6;
|
|
3009
|
-
const results = [];
|
|
3010
|
-
for (let index = 0; index < rows.length; index += CONCURRENCY) {
|
|
3011
|
-
const slice = rows.slice(index, index + CONCURRENCY);
|
|
3012
|
-
const settled = await Promise.all(slice.map(async (row) => {
|
|
3013
|
-
const info = await npmLatestVersion({ name: row.name, token });
|
|
3014
|
-
return {
|
|
3015
|
-
...row,
|
|
3016
|
-
latest: info.latest,
|
|
3017
|
-
error: info.error ?? null,
|
|
3018
|
-
outdated: info.latest !== null && !rangeSatisfied(row.range, info.latest),
|
|
3019
|
-
};
|
|
3020
|
-
}));
|
|
3021
|
-
results.push(...settled);
|
|
3022
|
-
}
|
|
3023
|
-
|
|
3024
|
-
return {
|
|
3025
|
-
path: file,
|
|
3026
|
-
name: typeof doc.name === 'string' ? doc.name : '',
|
|
3027
|
-
version: typeof doc.version === 'string' ? doc.version : '',
|
|
3028
|
-
items: results,
|
|
3029
|
-
total: results.length,
|
|
3030
|
-
outdated: results.filter((row) => row.outdated).length,
|
|
3031
|
-
failed: results.filter((row) => row.error !== null).length,
|
|
3032
|
-
};
|
|
3033
|
-
}
|
|
3034
|
-
|
|
3035
|
-
/**
|
|
3036
|
-
* `GET /npm/package` — one package's versions and dist-tags. /**
|
|
3037
|
-
* `GET /npm/package` — one package's versions and dist-tags.
|
|
3038
|
-
*
|
|
3039
|
-
* Public data, so no token is required; a token is still passed when one is
|
|
3040
|
-
* available so private/org packages resolve too.
|
|
3041
|
-
*
|
|
3042
|
-
* @param {object} query
|
|
3043
|
-
* @returns {Promise<object>}
|
|
3044
|
-
*/
|
|
3045
|
-
async npmPackage(query) {
|
|
3046
|
-
const name = requireString(query, 'name', '包名').trim();
|
|
3047
|
-
const account = await this.#store.activeNpmAccount();
|
|
3048
|
-
const result = await npmPackument({ name, token: account ? account.token : undefined });
|
|
3049
|
-
return result;
|
|
3050
|
-
}
|
|
3051
|
-
|
|
3052
|
-
/* ---------------- CONTRACT §3d: pre-push review ---------------- */ /* ---------------- CONTRACT §3d: pre-push review ---------------- */
|
|
3053
|
-
|
|
3054
|
-
/**
|
|
3055
|
-
* `GET /review/presets` — built-ins plus the user's saved prompts.
|
|
3056
|
-
*
|
|
3057
|
-
* Built-ins are code, never stored: wiping the saved list must not remove the
|
|
3058
|
-
* product's own opinion about what deserves checking.
|
|
3059
|
-
*
|
|
3060
|
-
* @returns {Promise<{builtin: object[], custom: object[], categories: object[]}>}
|
|
3061
|
-
*/
|
|
3062
|
-
async reviewPresets() {
|
|
3063
|
-
const custom = await this.#store.reviewPresets();
|
|
3064
|
-
return {
|
|
3065
|
-
builtin: BUILTIN_PRESETS.map((preset) => ({ ...preset, builtin: true })),
|
|
3066
|
-
custom,
|
|
3067
|
-
categories: REVIEW_CATEGORIES.map((category) => ({ ...category })),
|
|
3068
|
-
};
|
|
3069
|
-
}
|
|
3070
|
-
|
|
3071
|
-
/**
|
|
3072
|
-
* `POST /review/presets` — save (or replace) a user preset.
|
|
3073
|
-
* @param {object} body
|
|
3074
|
-
* @returns {Promise<{preset: object}>}
|
|
3075
|
-
*/
|
|
3076
|
-
async reviewPresetSave(body) {
|
|
3077
|
-
const title = requireString(body, 'title', '预设标题');
|
|
3078
|
-
const prompt = requireString(body, 'prompt', '提示词');
|
|
3079
|
-
const preset = await this.#store.saveReviewPreset({
|
|
3080
|
-
id: optionalString(body.id),
|
|
3081
|
-
title,
|
|
3082
|
-
prompt,
|
|
3083
|
-
description: optionalString(body.description) ?? '',
|
|
3084
|
-
category: optionalString(body.category) ?? 'custom',
|
|
3085
|
-
});
|
|
3086
|
-
return { preset };
|
|
3087
|
-
}
|
|
3088
|
-
|
|
3089
|
-
/**
|
|
3090
|
-
* `POST /review/presets/delete` — remove one saved preset.
|
|
3091
|
-
*
|
|
3092
|
-
* Built-ins are refused explicitly: they are not in the store, so a silent
|
|
3093
|
-
* "not found" would look like a bug to a user who just clicked delete.
|
|
3094
|
-
*
|
|
3095
|
-
* @param {object} body
|
|
3096
|
-
* @returns {Promise<{deleted: true}>}
|
|
3097
|
-
*/
|
|
3098
|
-
async reviewPresetDelete(body) {
|
|
3099
|
-
const id = requireString(body, 'id', '预设 id');
|
|
3100
|
-
if (BUILTIN_PRESETS.some((preset) => preset.id === id)) {
|
|
3101
|
-
throw httpError(409, 'CONFLICT', '内置审查项不能删除,只能在审查时取消勾选。');
|
|
3102
|
-
}
|
|
3103
|
-
const removed = await this.#store.deleteReviewPreset(id);
|
|
3104
|
-
if (!removed) throw httpError(404, 'NOT_FOUND', '找不到这条预设,可能已被删除。');
|
|
3105
|
-
return { deleted: true };
|
|
3106
|
-
}
|
|
3107
|
-
|
|
3108
|
-
/**
|
|
3109
|
-
* `GET /review/models` — provider/model/effort candidates for the pickers.
|
|
3110
|
-
*
|
|
3111
|
-
* Read from the host's `llm` service through `ctx.get`: it is optional, and a
|
|
3112
|
-
* composition without it must still serve the review UI (which then shows
|
|
3113
|
-
* "宿主未提供模型配置" and runs rule-based review only).
|
|
3114
|
-
*
|
|
3115
|
-
* @returns {Promise<{providers: object[], default: object|null}>}
|
|
3116
|
-
*/
|
|
3117
|
-
async reviewModels() {
|
|
3118
|
-
const llm = this.#llm();
|
|
3119
|
-
const providers = [];
|
|
3120
|
-
let fallback = null;
|
|
3121
|
-
if (llm) {
|
|
3122
|
-
try {
|
|
3123
|
-
const list = typeof llm.listProviders === 'function' ? llm.listProviders() : [];
|
|
3124
|
-
for (const provider of list) {
|
|
3125
|
-
let models = [];
|
|
3126
|
-
try {
|
|
3127
|
-
models = typeof llm.listModels === 'function' ? await llm.listModels(provider.id) : [];
|
|
3128
|
-
} catch {
|
|
3129
|
-
models = [];
|
|
3130
|
-
}
|
|
3131
|
-
const mapped = [];
|
|
3132
|
-
for (const model of models) {
|
|
3133
|
-
let efforts = [];
|
|
3134
|
-
let defaultEffort;
|
|
3135
|
-
try {
|
|
3136
|
-
const info = typeof llm.resolveModelInfo === 'function'
|
|
3137
|
-
? await llm.resolveModelInfo(provider.id, model.id)
|
|
3138
|
-
: null;
|
|
3139
|
-
const reasoning = info && info.reasoning ? info.reasoning : null;
|
|
3140
|
-
if (reasoning && Array.isArray(reasoning.efforts)) {
|
|
3141
|
-
efforts = reasoning.efforts.map((effort) => ({ id: effort.id, name: effort.name }));
|
|
3142
|
-
}
|
|
3143
|
-
if (reasoning && reasoning.defaultEffort) defaultEffort = reasoning.defaultEffort;
|
|
3144
|
-
} catch {
|
|
3145
|
-
efforts = [];
|
|
3146
|
-
}
|
|
3147
|
-
mapped.push({ id: model.id, name: model.name || model.id, efforts, defaultEffort });
|
|
3148
|
-
}
|
|
3149
|
-
providers.push({ id: provider.id, name: provider.name || provider.id, models: mapped });
|
|
3150
|
-
if (fallback === null && mapped.length > 0) {
|
|
3151
|
-
fallback = { provider: provider.id, model: mapped[0].id };
|
|
3152
|
-
}
|
|
3153
|
-
}
|
|
3154
|
-
} catch {
|
|
3155
|
-
// A provider directory that cannot enumerate must not break the panel.
|
|
3156
|
-
}
|
|
3157
|
-
}
|
|
3158
|
-
return { providers, default: fallback };
|
|
3159
|
-
}
|
|
3160
|
-
|
|
3161
|
-
/**
|
|
3162
|
-
* `POST /review/project` — 一次审查覆盖整个项目。
|
|
3163
|
-
*
|
|
3164
|
-
* 同一份代码既是 git 的改动源,也是 npm 的发布内容。分别跑两次审查
|
|
3165
|
-
* 既慢又会让同一问题报两遍。这里一次收齐:
|
|
3166
|
-
*
|
|
3167
|
-
* - git:未提交改动(存在仓库时)
|
|
3168
|
-
* - npm:npm pack 会打进去的文件(存在 package.json 时)
|
|
3169
|
-
*
|
|
3170
|
-
* 结果按 scope 标注来源,界面据此分组;用户在各自插件里提交即可。
|
|
3171
|
-
*
|
|
3172
|
-
* @param {object} body `{ path, presetIds, customPrompt, provider, model,
|
|
3173
|
-
* reasoningEffort, includeGit, includePack, maxFiles }`
|
|
3174
|
-
* @returns {Promise<object>}
|
|
3175
|
-
*/
|
|
3176
|
-
async reviewProject(body) {
|
|
3177
|
-
const dir = typeof body.path === 'string' && body.path.trim() !== ''
|
|
3178
|
-
? body.path.trim()
|
|
3179
|
-
: process.cwd();
|
|
3180
|
-
|
|
3181
|
-
const collections = [];
|
|
3182
|
-
const skipped = [];
|
|
3183
|
-
|
|
3184
|
-
/* ---- 1. git 改动 ---- */
|
|
3185
|
-
const wantGit = body.includeGit !== false;
|
|
3186
|
-
if (wantGit) {
|
|
3187
|
-
const gitDir = path.join(dir, '.git');
|
|
3188
|
-
let isRepo = false;
|
|
3189
|
-
try { isRepo = (await stat(gitDir)).isDirectory(); } catch { isRepo = false; }
|
|
3190
|
-
if (isRepo) {
|
|
3191
|
-
try {
|
|
3192
|
-
const { runner, secrets } = await this.#runnerAndSecrets();
|
|
3193
|
-
const root = (await runner.assertRepo(dir, { secrets })).root;
|
|
3194
|
-
const changes = await collectReviewChanges(runner, root, {
|
|
3195
|
-
staged: false,
|
|
3196
|
-
maxFiles: Number.isFinite(body.maxFiles) ? Number(body.maxFiles) : 60,
|
|
3197
|
-
secrets,
|
|
3198
|
-
});
|
|
3199
|
-
for (const chunk of changes.chunks) {
|
|
3200
|
-
collections.push({ scope: 'git', path: chunk.path, text: chunk.text });
|
|
3201
|
-
}
|
|
3202
|
-
if (changes.truncated) skipped.push({ scope: 'git', reason: '改动过多,已截断' });
|
|
3203
|
-
} catch (error) {
|
|
3204
|
-
skipped.push({ scope: 'git', reason: error.message });
|
|
3205
|
-
}
|
|
3206
|
-
} else {
|
|
3207
|
-
skipped.push({ scope: 'git', reason: '不是 git 仓库' });
|
|
3208
|
-
}
|
|
3209
|
-
}
|
|
3210
|
-
|
|
3211
|
-
/* ---- 2. npm 包内容 ---- */
|
|
3212
|
-
const wantPack = body.includePack !== false;
|
|
3213
|
-
let packed = null;
|
|
3214
|
-
if (wantPack) {
|
|
3215
|
-
try {
|
|
3216
|
-
await readFile(path.join(dir, 'package.json'), 'utf8');
|
|
3217
|
-
const runner = this.#npmRunner();
|
|
3218
|
-
packed = mapPackResult(parsePackJson(
|
|
3219
|
-
(await runner.run(['pack', '--dry-run', '--json'], { cwd: dir })).stdout,
|
|
3220
|
-
));
|
|
3221
|
-
const maxBytes = MAX_FILE_BYTES;
|
|
3222
|
-
for (const row of packed.files) {
|
|
3223
|
-
const rel = row.path.replace(/\/$/, '');
|
|
3224
|
-
if (/(^|\/)(node_modules|\.git)\//.test(rel)) continue;
|
|
3225
|
-
// 已经在 git 里出现过的文件不重复审:同一份内容只报一次。
|
|
3226
|
-
if (collections.some((row2) => row2.path === rel)) continue;
|
|
3227
|
-
if (row.size > maxBytes) {
|
|
3228
|
-
skipped.push({ scope: 'npm', reason: `${rel} 过大` });
|
|
3229
|
-
continue;
|
|
3230
|
-
}
|
|
3231
|
-
try {
|
|
3232
|
-
const text = await readFile(path.join(dir, rel), 'utf8');
|
|
3233
|
-
if (text.includes('\u0000')) continue;
|
|
3234
|
-
collections.push({ scope: 'npm', path: rel, text });
|
|
3235
|
-
} catch { /* 读不到就跳过 */ }
|
|
3236
|
-
}
|
|
3237
|
-
} catch (error) {
|
|
3238
|
-
skipped.push({ scope: 'npm', reason: error.code === 'ENOENT' ? '没有 package.json' : error.message });
|
|
3239
|
-
}
|
|
3240
|
-
}
|
|
3241
|
-
|
|
3242
|
-
/* ---- 3. 规则扫描 ---- */
|
|
3243
|
-
const ruleFindings = [];
|
|
3244
|
-
for (const row of collections) {
|
|
3245
|
-
for (const finding of scanSecrets(row.text, { file: row.path })) {
|
|
3246
|
-
ruleFindings.push({ ...normalizeFinding(finding), scope: row.scope });
|
|
3247
|
-
}
|
|
3248
|
-
}
|
|
3249
|
-
|
|
3250
|
-
/* ---- 4. 模型审查(一次覆盖全部内容) ---- */
|
|
3251
|
-
const presetIds = Array.isArray(body.presetIds)
|
|
3252
|
-
? body.presetIds.filter((id) => typeof id === 'string' && id !== '')
|
|
3253
|
-
: [];
|
|
3254
|
-
const stored = await this.#store.reviewPresets();
|
|
3255
|
-
const chosen = [
|
|
3256
|
-
...BUILTIN_PRESETS.filter((preset) => presetIds.includes(preset.id)),
|
|
3257
|
-
...stored.filter((preset) => presetIds.includes(preset.id)),
|
|
3258
|
-
];
|
|
3259
|
-
const customPrompt = optionalString(body.customPrompt) ?? '';
|
|
3260
|
-
|
|
3261
|
-
const llm = this.#llm();
|
|
3262
|
-
let provider = optionalString(body.provider);
|
|
3263
|
-
let model = optionalString(body.model);
|
|
3264
|
-
if (llm && (!provider || !model)) {
|
|
3265
|
-
try {
|
|
3266
|
-
const fallback = await this.reviewModels();
|
|
3267
|
-
if (fallback.default) {
|
|
3268
|
-
provider = provider ?? fallback.default.provider;
|
|
3269
|
-
model = model ?? fallback.default.model;
|
|
3270
|
-
}
|
|
3271
|
-
} catch { /* 保留调用方的值 */ }
|
|
3272
|
-
}
|
|
3273
|
-
|
|
3274
|
-
let modelFindings = [];
|
|
3275
|
-
let summary = '';
|
|
3276
|
-
let usage;
|
|
3277
|
-
let degraded = false;
|
|
3278
|
-
|
|
3279
|
-
const scopes = new Set(collections.map((row) => row.scope));
|
|
3280
|
-
if (collections.length === 0) {
|
|
3281
|
-
summary = '没有可审查的内容:既没有未提交的 git 改动,也没有可打包的 npm 文件。';
|
|
3282
|
-
} else if (!llm) {
|
|
3283
|
-
degraded = true;
|
|
3284
|
-
summary = '宿主未提供 llm 服务,本次只执行了规则检查(敏感信息扫描)。';
|
|
3285
|
-
} else if (!provider || !model) {
|
|
3286
|
-
degraded = true;
|
|
3287
|
-
summary = '未找到可用的模型,本次只执行了规则检查(敏感信息扫描)。';
|
|
3288
|
-
} else {
|
|
3289
|
-
const instructions = [
|
|
3290
|
-
...chosen.map((preset) => `## ${preset.title}\n${preset.prompt}`),
|
|
3291
|
-
...(customPrompt ? [`## 用户补充要求\n${customPrompt}`] : []),
|
|
3292
|
-
].join('\n\n');
|
|
3293
|
-
|
|
3294
|
-
const promptParts = [];
|
|
3295
|
-
if (instructions !== '') promptParts.push(instructions);
|
|
3296
|
-
promptParts.push('## 审查范围');
|
|
3297
|
-
promptParts.push('这是一个项目的完整待发布内容,包含两部分:'
|
|
3298
|
-
+ 'git 未提交改动(即将提交)和 npm 包内容(即将发布)。'
|
|
3299
|
-
+ '同一条问题只报一次,报告时说明它影响哪一部分。'
|
|
3300
|
-
+ '未列出的文件不代表项目缺少文件,只代表本次不涉及。');
|
|
3301
|
-
promptParts.push(`## 文件(${collections.length} 个)`);
|
|
3302
|
-
promptParts.push(collections.map((row) => `- [${row.scope}] ${row.path}`).join('\n'));
|
|
3303
|
-
promptParts.push('## 内容');
|
|
3304
|
-
promptParts.push(collections.map((row) =>
|
|
3305
|
-
`### [${row.scope}] ${row.path}\n\`\`\`\n${row.text}\n\`\`\``).join('\n\n'));
|
|
3306
|
-
|
|
3307
|
-
try {
|
|
3308
|
-
const result = await runModelReview(llm, {
|
|
3309
|
-
provider,
|
|
3310
|
-
model,
|
|
3311
|
-
reasoningEffort: optionalString(body.reasoningEffort),
|
|
3312
|
-
prompt: promptParts.join('\n\n'),
|
|
3313
|
-
});
|
|
3314
|
-
modelFindings = result.findings.map((row) => ({
|
|
3315
|
-
...normalizeFinding(row),
|
|
3316
|
-
scope: row.scope || (scopes.size > 1 ? 'both' : [...scopes][0] || 'project'),
|
|
3317
|
-
}));
|
|
3318
|
-
summary = result.summary;
|
|
3319
|
-
usage = result.usage;
|
|
3320
|
-
} catch (error) {
|
|
3321
|
-
degraded = true;
|
|
3322
|
-
summary = `模型审查失败(${String(error && error.message ? error.message : error)}),本次只执行了规则检查。`;
|
|
3323
|
-
}
|
|
3324
|
-
}
|
|
3325
|
-
|
|
3326
|
-
const findings = sortFindings([...ruleFindings, ...modelFindings]);
|
|
3327
|
-
if (summary === '') {
|
|
3328
|
-
summary = findings.length === 0 ? '未发现明显问题。' : `共发现 ${findings.length} 处需要关注的问题。`;
|
|
3329
|
-
}
|
|
3330
|
-
|
|
3331
|
-
return {
|
|
3332
|
-
reviewId: `project_${Date.now().toString(36)}`,
|
|
3333
|
-
scope: 'project',
|
|
3334
|
-
model: provider && model ? { provider, model, label: `${provider} / ${model}` } : null,
|
|
3335
|
-
effort: optionalString(body.reasoningEffort) ?? null,
|
|
3336
|
-
files: collections.map((row) => ({ path: row.path, scope: row.scope })),
|
|
3337
|
-
findings,
|
|
3338
|
-
summary,
|
|
3339
|
-
usage,
|
|
3340
|
-
degraded,
|
|
3341
|
-
skipped,
|
|
3342
|
-
pack: packed
|
|
3343
|
-
? { totalFiles: packed.totalFiles, size: packed.size, unpackedSize: packed.unpackedSize }
|
|
3344
|
-
: null,
|
|
3345
|
-
};
|
|
3346
|
-
}
|
|
3347
|
-
|
|
3348
|
-
/**
|
|
3349
|
-
* `POST /review/run` — review the changes that would be pushed. /**
|
|
3350
|
-
* `POST /review/run` — review the changes that would be pushed.
|
|
3351
|
-
*
|
|
3352
|
-
* Two passes, ALWAYS in this order and with this failure posture:
|
|
3353
|
-
* 1. rule scan (cheap, deterministic, never skipped);
|
|
3354
|
-
* 2. model review (skipped or degraded when `llm` is unavailable).
|
|
3355
|
-
* A review that cannot reach a model still returns `ok` with the rule
|
|
3356
|
-
* findings: the whole point is to inform a push, never to block one.
|
|
3357
|
-
*
|
|
3358
|
-
* @param {object} body
|
|
3359
|
-
* @returns {Promise<object>}
|
|
3360
|
-
*/
|
|
3361
|
-
async reviewRun(body) {
|
|
3362
|
-
const path = requireString(body, 'path', '仓库路径');
|
|
3363
|
-
const { settings, runner, secrets } = await this.#runnerAndSecrets();
|
|
3364
|
-
const root = (await runner.assertRepo(path, { secrets })).root;
|
|
3365
|
-
|
|
3366
|
-
const presetIds = Array.isArray(body.presetIds)
|
|
3367
|
-
? body.presetIds.filter((id) => typeof id === 'string' && id !== '')
|
|
3368
|
-
: [];
|
|
3369
|
-
const custom = await this.#store.reviewPresets();
|
|
3370
|
-
const chosen = [
|
|
3371
|
-
...BUILTIN_PRESETS.filter((preset) => presetIds.includes(preset.id)),
|
|
3372
|
-
...custom.filter((preset) => presetIds.includes(preset.id)),
|
|
3373
|
-
];
|
|
3374
|
-
const customPrompt = optionalString(body.customPrompt) ?? '';
|
|
3375
|
-
|
|
3376
|
-
const changes = await collectReviewChanges(runner, root, {
|
|
3377
|
-
staged: optionalBool(body.staged, false),
|
|
3378
|
-
includeFiles: Array.isArray(body.includeFiles) ? body.includeFiles : undefined,
|
|
3379
|
-
maxFiles: Number.isFinite(body.maxFiles) ? body.maxFiles : 60,
|
|
3380
|
-
secrets,
|
|
3381
|
-
});
|
|
3382
|
-
|
|
3383
|
-
// ---- pass 1: rules ------------------------------------------------
|
|
3384
|
-
const ruleFindings = [];
|
|
3385
|
-
for (const chunk of changes.chunks) {
|
|
3386
|
-
ruleFindings.push(...scanSecrets(chunk.text, { file: chunk.path }));
|
|
3387
|
-
}
|
|
3388
|
-
|
|
3389
|
-
// ---- pass 2: the model (best effort) ------------------------------
|
|
3390
|
-
const llm = this.#llm();
|
|
3391
|
-
const wantedProvider = optionalString(body.provider);
|
|
3392
|
-
const wantedModel = optionalString(body.model);
|
|
3393
|
-
let provider = wantedProvider;
|
|
3394
|
-
let model = wantedModel;
|
|
3395
|
-
if (llm && (!provider || !model)) {
|
|
3396
|
-
try {
|
|
3397
|
-
const fallback = await this.reviewModels();
|
|
3398
|
-
if (fallback.default) {
|
|
3399
|
-
provider = provider ?? fallback.default.provider;
|
|
3400
|
-
model = model ?? fallback.default.model;
|
|
3401
|
-
}
|
|
3402
|
-
} catch {
|
|
3403
|
-
// keep the caller's values; runModelReview will decline cleanly
|
|
3404
|
-
}
|
|
3405
|
-
}
|
|
3406
|
-
|
|
3407
|
-
const instructions = [
|
|
3408
|
-
...chosen.map((preset) => `## ${preset.title}\n${preset.prompt}`),
|
|
3409
|
-
...(customPrompt ? [`## 用户补充要求\n${customPrompt}`] : []),
|
|
3410
|
-
].join('\n\n');
|
|
3411
|
-
|
|
3412
|
-
const promptParts = [];
|
|
3413
|
-
if (instructions !== '') promptParts.push(instructions);
|
|
3414
|
-
promptParts.push(`## 变更文件(${changes.files.length} 个)`);
|
|
3415
|
-
promptParts.push(changes.files.map((file) => `- ${file.path}${file.skipped ? `(未送审:${file.skipped})` : ''}`).join('\n'));
|
|
3416
|
-
promptParts.push('## 差异');
|
|
3417
|
-
promptParts.push(changes.patch === '' ? '(没有可审查的改动)' : changes.patch);
|
|
3418
|
-
|
|
3419
|
-
/* What the model is looking at, and — just as important — what it is
|
|
3420
|
-
* NOT looking at. Without this a size-truncated patch reads as "these
|
|
3421
|
-
* files are missing from the project", which is a false alarm on exactly
|
|
3422
|
-
* the release review that matters most. */
|
|
3423
|
-
promptParts.splice(2, 0, '## 审查范围');
|
|
3424
|
-
promptParts.splice(3, 0, changes.scope === 'outgoing'
|
|
3425
|
-
? `当前分支有 ${changes.range ? changes.range.count : '若干'} 个提交尚未推送,本次审查的是它们相对远端的差异。`
|
|
3426
|
-
: '本次审查的是工作区中尚未提交的改动。');
|
|
3427
|
-
promptParts.splice(4, 0, '注意:文件列表只包含本次改动涉及的文件。未出现在列表中的文件属于仓库既有内容,' +
|
|
3428
|
-
'不代表它们不存在、未提交或不随包发布——不要据此推断项目缺少文件。');
|
|
3429
|
-
|
|
3430
|
-
if (changes.truncated === true) {
|
|
3431
|
-
promptParts.splice(5, 0, '严重提示:本次差异因体积限制被截断,你看到的内容并不完整。' +
|
|
3432
|
-
'不要因为某个改动看起来缺失就断定功能不完整,只针对你实际看到的内容报告问题。');
|
|
3433
|
-
}
|
|
3434
|
-
|
|
3435
|
-
let modelFindings = [];
|
|
3436
|
-
let summary = '';
|
|
3437
|
-
let usage;
|
|
3438
|
-
let degraded = false;
|
|
3439
|
-
const effectiveProvider = provider;
|
|
3440
|
-
const effectiveModel = model;
|
|
3441
|
-
|
|
3442
|
-
if (changes.patch === '') {
|
|
3443
|
-
summary = '没有检测到待推送的改动。';
|
|
3444
|
-
} else if (!llm) {
|
|
3445
|
-
degraded = true;
|
|
3446
|
-
summary = '宿主未提供 llm 服务,本次只执行了规则检查(敏感信息扫描)。';
|
|
3447
|
-
} else if (!effectiveProvider || !effectiveModel) {
|
|
3448
|
-
degraded = true;
|
|
3449
|
-
summary = '未找到可用的模型,本次只执行了规则检查(敏感信息扫描)。';
|
|
3450
|
-
} else {
|
|
3451
|
-
try {
|
|
3452
|
-
const result = await runModelReview(llm, {
|
|
3453
|
-
provider: effectiveProvider,
|
|
3454
|
-
model: effectiveModel,
|
|
3455
|
-
reasoningEffort: optionalString(body.reasoningEffort),
|
|
3456
|
-
prompt: promptParts.join('\n\n'),
|
|
3457
|
-
});
|
|
3458
|
-
modelFindings = result.findings.map(normalizeFinding);
|
|
3459
|
-
summary = result.summary;
|
|
3460
|
-
usage = result.usage;
|
|
3461
|
-
} catch (error) {
|
|
3462
|
-
degraded = true;
|
|
3463
|
-
summary = `模型审查失败(${String(error && error.message ? error.message : error)}),本次只执行了规则检查。`;
|
|
3464
|
-
}
|
|
3465
|
-
}
|
|
3466
|
-
|
|
3467
|
-
const findings = sortFindings([...ruleFindings, ...modelFindings]);
|
|
3468
|
-
if (summary === '') {
|
|
3469
|
-
summary = findings.length === 0 ? '未发现明显问题。' : `共发现 ${findings.length} 处需要关注的问题。`;
|
|
3470
|
-
}
|
|
3471
|
-
|
|
3472
|
-
return {
|
|
3473
|
-
reviewId: `review_${Date.now().toString(36)}`,
|
|
3474
|
-
model: effectiveProvider && effectiveModel
|
|
3475
|
-
? { provider: effectiveProvider, model: effectiveModel, label: `${effectiveProvider} / ${effectiveModel}` }
|
|
3476
|
-
: null,
|
|
3477
|
-
effort: optionalString(body.reasoningEffort) ?? null,
|
|
3478
|
-
files: changes.files,
|
|
3479
|
-
findings,
|
|
3480
|
-
summary,
|
|
3481
|
-
usage,
|
|
3482
|
-
degraded,
|
|
3483
|
-
truncated: changes.truncated,
|
|
3484
|
-
// "working" = uncommitted changes; "outgoing" = the commits a push
|
|
3485
|
-
// would send. The two are different questions and the panel says which
|
|
3486
|
-
// one was answered, so a clean result is never mistaken for the other.
|
|
3487
|
-
scope: changes.scope === 'outgoing' ? 'outgoing' : 'working',
|
|
3488
|
-
outgoingCommits: changes.range ? changes.range.count : 0,
|
|
3489
|
-
};
|
|
3490
|
-
}
|
|
3491
|
-
|
|
3492
|
-
/* ---------------- Cloudflare module (CONTRACT §6) ---------------- */
|
|
3493
|
-
|
|
3494
|
-
/**
|
|
3495
|
-
* 当前 Cloudflare 账号(带令牌),缺失时给出可执行提示而不是空结果。
|
|
3496
|
-
* @returns {Promise<object>}
|
|
3497
|
-
*/
|
|
3498
|
-
async #requireCloudflareAccount() {
|
|
3499
|
-
const account = await this.#store.activeCloudflareAccount();
|
|
3500
|
-
if (!account) {
|
|
3501
|
-
throw httpError(401, 'NO_ACCOUNT', '还没有登录 Cloudflare。请在 设置 › Cloudflare 中添加一个 API Token 或 Global API Key。');
|
|
3502
|
-
}
|
|
3503
|
-
return account;
|
|
3504
|
-
}
|
|
3505
|
-
|
|
3506
|
-
/**
|
|
3507
|
-
* 把一条已存账号折算成 Cloudflare 客户端要的凭据对象。
|
|
3508
|
-
* @param {object} account store 里的账号记录
|
|
3509
|
-
* @returns {{kind: string, token?: string, email?: string, key?: string}}
|
|
3510
|
-
*/
|
|
3511
|
-
#cloudflareCredential(account) {
|
|
3512
|
-
if (account.authKind === 'global') {
|
|
3513
|
-
return { kind: 'global', email: account.email, key: account.token };
|
|
3514
|
-
}
|
|
3515
|
-
return { kind: 'token', token: account.token };
|
|
3516
|
-
}
|
|
3517
|
-
|
|
3518
|
-
/**
|
|
3519
|
-
* 当前账号的 accountId;账号存在但还没选账户时,自动列账户并取第一个。
|
|
3520
|
-
* @returns {Promise<{account: object, accountId: string}>}
|
|
3521
|
-
*/
|
|
3522
|
-
async #cloudflareContext() {
|
|
3523
|
-
const account = await this.#requireCloudflareAccount();
|
|
3524
|
-
if (account.accountId !== '') {
|
|
3525
|
-
return { account, accountId: account.accountId };
|
|
3526
|
-
}
|
|
3527
|
-
const accounts = await listCfAccounts(this.#cloudflareCredential(account));
|
|
3528
|
-
if (accounts.length === 0) {
|
|
3529
|
-
throw httpError(400, 'NO_ACCOUNT', '这个 Cloudflare 凭据下没有可用的账户。');
|
|
3530
|
-
}
|
|
3531
|
-
const chosen = accounts[0];
|
|
3532
|
-
await this.#store.updateCloudflareAccount(account.id, {
|
|
3533
|
-
accountId: chosen.id,
|
|
3534
|
-
accountName: chosen.name,
|
|
3535
|
-
});
|
|
3536
|
-
return { account, accountId: chosen.id };
|
|
3537
|
-
}
|
|
3538
|
-
|
|
3539
|
-
/**
|
|
3540
|
-
* `GET /cf/accounts` — Cloudflare 账号列表(不带令牌)。
|
|
3541
|
-
* @returns {Promise<object>}
|
|
3542
|
-
*/
|
|
3543
|
-
async cloudflareAccounts() {
|
|
3544
|
-
return this.#store.cloudflareAccounts();
|
|
3545
|
-
}
|
|
3546
|
-
|
|
3547
|
-
/**
|
|
3548
|
-
* `POST /cf/account` — 校验凭据后存储。
|
|
3549
|
-
*
|
|
3550
|
-
* 支持两种登录方式:
|
|
3551
|
-
* - `{ token }` —— API Token(cfut_ / cfat_ 或旧 40 位字母数字)
|
|
3552
|
-
* - `{ email, key }` —— Global API Key(cfk_ 或旧 37-45 位十六进制,全权限)
|
|
3553
|
-
*
|
|
3554
|
-
* @param {object} body `{ token?, email?, key?, authKind?, label? }`
|
|
3555
|
-
* @returns {Promise<object>}
|
|
3556
|
-
*/
|
|
3557
|
-
async cloudflareAccountAdd(body) {
|
|
3558
|
-
const wantsGlobal = optionalString(body.key) !== undefined
|
|
3559
|
-
|| String(body.authKind ?? '') === 'global';
|
|
3560
|
-
|
|
3561
|
-
let credential;
|
|
3562
|
-
if (wantsGlobal) {
|
|
3563
|
-
const email = requireString(body, 'email', 'Cloudflare 账户邮箱').trim();
|
|
3564
|
-
const key = requireString(body, 'key', 'Global API Key').trim();
|
|
3565
|
-
credential = { kind: 'global', email, key };
|
|
3566
|
-
} else {
|
|
3567
|
-
const token = requireString(body, 'token', 'Cloudflare API Token').trim();
|
|
3568
|
-
credential = { kind: 'token', token };
|
|
3569
|
-
}
|
|
3570
|
-
|
|
3571
|
-
const verified = await verifyCfToken(credential);
|
|
3572
|
-
|
|
3573
|
-
let accountName = '';
|
|
3574
|
-
let accountId = '';
|
|
3575
|
-
try {
|
|
3576
|
-
const accounts = await listCfAccounts(credential);
|
|
3577
|
-
if (accounts.length > 0) {
|
|
3578
|
-
accountId = accounts[0].id;
|
|
3579
|
-
accountName = accounts[0].name;
|
|
3580
|
-
}
|
|
3581
|
-
} catch { /* 账户列表失败不阻止登录;账号卡里仍可手动触发 */ }
|
|
3582
|
-
|
|
3583
|
-
const fallback = credential.kind === 'global'
|
|
3584
|
-
? (verified.email || credential.email)
|
|
3585
|
-
: (accountName || 'Cloudflare 账号');
|
|
3586
|
-
const label = optionalString(body.label) ?? fallback;
|
|
3587
|
-
|
|
3588
|
-
return this.#store.saveCloudflareAccount({
|
|
3589
|
-
authKind: credential.kind,
|
|
3590
|
-
login: label,
|
|
3591
|
-
email: credential.kind === 'global' ? credential.email : '',
|
|
3592
|
-
token: credential.kind === 'global' ? credential.key : credential.token,
|
|
3593
|
-
accountId,
|
|
3594
|
-
accountName,
|
|
3595
|
-
});
|
|
3596
|
-
}
|
|
3597
|
-
|
|
3598
|
-
/**
|
|
3599
|
-
* `POST /cf/account/remove`.
|
|
3600
|
-
* @param {object} body `{ id }`
|
|
3601
|
-
* @returns {Promise<{removed: boolean}>}
|
|
3602
|
-
*/
|
|
3603
|
-
async cloudflareAccountRemove(body) {
|
|
3604
|
-
const id = requireString(body, 'id', '账号 id');
|
|
3605
|
-
const removed = await this.#store.deleteCloudflareAccount(id);
|
|
3606
|
-
if (!removed) throw httpError(404, 'NOT_FOUND', '找不到这个 Cloudflare 账号,可能已被移除。');
|
|
3607
|
-
return { removed: true };
|
|
3608
|
-
}
|
|
3609
|
-
|
|
3610
|
-
/**
|
|
3611
|
-
* `POST /cf/account/active`.
|
|
3612
|
-
* @param {object} body `{ id }`
|
|
3613
|
-
* @returns {Promise<{activeId: string}>}
|
|
3614
|
-
*/
|
|
3615
|
-
async cloudflareAccountActive(body) {
|
|
3616
|
-
const id = requireString(body, 'id', '账号 id');
|
|
3617
|
-
const ok = await this.#store.setActiveCloudflareAccount(id);
|
|
3618
|
-
if (!ok) throw httpError(404, 'NOT_FOUND', '找不到这个 Cloudflare 账号。');
|
|
3619
|
-
return { activeId: id };
|
|
3620
|
-
}
|
|
3621
|
-
|
|
3622
|
-
/**
|
|
3623
|
-
* `POST /cf/account/select` — 登录后选择 Cloudflare account。
|
|
3624
|
-
* @param {object} body `{ accountId, accountName }`
|
|
3625
|
-
* @returns {Promise<object>}
|
|
3626
|
-
*/
|
|
3627
|
-
async cloudflareAccountSelect(body) {
|
|
3628
|
-
const account = await this.#requireCloudflareAccount();
|
|
3629
|
-
const accountId = requireString(body, 'accountId', 'Cloudflare 账户 id');
|
|
3630
|
-
return this.#store.updateCloudflareAccount(account.id, {
|
|
3631
|
-
accountId,
|
|
3632
|
-
accountName: optionalString(body.accountName) ?? '',
|
|
3633
|
-
});
|
|
3634
|
-
}
|
|
3635
|
-
|
|
3636
|
-
/**
|
|
3637
|
-
* `GET /cf/accounts/list` — 当前凭据可访问的 Cloudflare 账户(选择器用)。
|
|
3638
|
-
* @returns {Promise<object>}
|
|
3639
|
-
*/
|
|
3640
|
-
async cloudflareAccountList() {
|
|
3641
|
-
const account = await this.#requireCloudflareAccount();
|
|
3642
|
-
const items = await listCfAccounts(this.#cloudflareCredential(account));
|
|
3643
|
-
return { items, activeAccountId: account.accountId };
|
|
3644
|
-
}
|
|
3645
|
-
|
|
3646
|
-
/**
|
|
3647
|
-
* `GET /cf/overview` — 设置页项目概览卡的数据源。
|
|
3648
|
-
* @returns {Promise<object>}
|
|
3649
|
-
*/
|
|
3650
|
-
async cloudflareOverview() {
|
|
3651
|
-
const { account, accountId } = await this.#cloudflareContext();
|
|
3652
|
-
const result = await cfOverview(this.#cloudflareCredential(account), accountId);
|
|
3653
|
-
await this.#store.touchCloudflareAccount(account.id);
|
|
3654
|
-
return {
|
|
3655
|
-
accountId,
|
|
3656
|
-
accountName: account.accountName || accountId,
|
|
3657
|
-
...result,
|
|
3658
|
-
};
|
|
3659
|
-
}
|
|
3660
|
-
|
|
3661
|
-
/**
|
|
3662
|
-
* `GET /cf/projects` — Pages 项目列表。
|
|
3663
|
-
* @returns {Promise<object>}
|
|
3664
|
-
*/
|
|
3665
|
-
async cloudflareProjects() {
|
|
3666
|
-
const { account, accountId } = await this.#cloudflareContext();
|
|
3667
|
-
const items = await listPagesProjects(this.#cloudflareCredential(account), accountId);
|
|
3668
|
-
await this.#store.touchCloudflareAccount(account.id);
|
|
3669
|
-
return { items, accountId };
|
|
3670
|
-
}
|
|
3671
|
-
|
|
3672
|
-
/**
|
|
3673
|
-
* `POST /cf/projects/create`.
|
|
3674
|
-
* @param {object} body `{ name, productionBranch? }`
|
|
3675
|
-
* @returns {Promise<object>}
|
|
3676
|
-
*/
|
|
3677
|
-
async cloudflareProjectCreate(body) {
|
|
3678
|
-
const { account, accountId } = await this.#cloudflareContext();
|
|
3679
|
-
const name = requireString(body, 'name', '项目名');
|
|
3680
|
-
const project = await createPagesProject(
|
|
3681
|
-
this.#cloudflareCredential(account),
|
|
3682
|
-
accountId,
|
|
3683
|
-
name,
|
|
3684
|
-
optionalString(body.productionBranch) ?? 'main',
|
|
3685
|
-
);
|
|
3686
|
-
await this.#store.touchCloudflareAccount(account.id);
|
|
3687
|
-
return { project };
|
|
3688
|
-
}
|
|
3689
|
-
|
|
3690
|
-
/**
|
|
3691
|
-
* `POST /cf/projects/delete` — 危险操作,需 `confirm: true`。
|
|
3692
|
-
* @param {object} body `{ name, confirm }`
|
|
3693
|
-
* @returns {Promise<{deleted: boolean}>}
|
|
3694
|
-
*/
|
|
3695
|
-
async cloudflareProjectDelete(body) {
|
|
3696
|
-
const { account, accountId } = await this.#cloudflareContext();
|
|
3697
|
-
const name = requireString(body, 'name', '项目名');
|
|
3698
|
-
if (optionalBool(body.confirm, false) !== true) {
|
|
3699
|
-
throw httpError(
|
|
3700
|
-
409,
|
|
3701
|
-
'CONFLICT',
|
|
3702
|
-
`删除 Pages 项目 ${name} 会移除它的所有部署与域名绑定,无法撤销。请确认后再执行(confirm: true)。`,
|
|
3703
|
-
);
|
|
3704
|
-
}
|
|
3705
|
-
const result = await deletePagesProject(this.#cloudflareCredential(account), accountId, name);
|
|
3706
|
-
await this.#store.touchCloudflareAccount(account.id);
|
|
3707
|
-
return result;
|
|
3708
|
-
}
|
|
3709
|
-
|
|
3710
|
-
/**
|
|
3711
|
-
* `GET /cf/workers` — Workers 列表。
|
|
3712
|
-
* @returns {Promise<object>}
|
|
3713
|
-
*/
|
|
3714
|
-
async cloudflareWorkers() {
|
|
3715
|
-
const { account, accountId } = await this.#cloudflareContext();
|
|
3716
|
-
const items = await listWorkers(this.#cloudflareCredential(account), accountId);
|
|
3717
|
-
await this.#store.touchCloudflareAccount(account.id);
|
|
3718
|
-
return { items, accountId };
|
|
3719
|
-
}
|
|
3720
|
-
|
|
3721
|
-
/**
|
|
3722
|
-
* `POST /cf/workers/delete` — 危险操作,需 `confirm: true`。
|
|
3723
|
-
* @param {object} body `{ name, confirm }`
|
|
3724
|
-
* @returns {Promise<{deleted: boolean}>}
|
|
3725
|
-
*/
|
|
3726
|
-
async cloudflareWorkerDelete(body) {
|
|
3727
|
-
const { account, accountId } = await this.#cloudflareContext();
|
|
3728
|
-
const name = requireString(body, 'name', 'Worker 名');
|
|
3729
|
-
if (optionalBool(body.confirm, false) !== true) {
|
|
3730
|
-
throw httpError(
|
|
3731
|
-
409,
|
|
3732
|
-
'CONFLICT',
|
|
3733
|
-
`删除 Worker ${name} 会移除它的线上代码,无法撤销。请确认后再执行(confirm: true)。`,
|
|
3734
|
-
);
|
|
3735
|
-
}
|
|
3736
|
-
const result = await deleteWorker(this.#cloudflareCredential(account), accountId, name);
|
|
3737
|
-
await this.#store.touchCloudflareAccount(account.id);
|
|
3738
|
-
return result;
|
|
3739
|
-
}
|
|
3740
|
-
|
|
3741
|
-
/**
|
|
3742
|
-
* `GET /cf/zones` — 域名列表。
|
|
3743
|
-
* @returns {Promise<object>}
|
|
3744
|
-
*/
|
|
3745
|
-
async cloudflareZones() {
|
|
3746
|
-
const { account, accountId } = await this.#cloudflareContext();
|
|
3747
|
-
const items = await listZones(this.#cloudflareCredential(account), accountId);
|
|
3748
|
-
await this.#store.touchCloudflareAccount(account.id);
|
|
3749
|
-
return { items, accountId };
|
|
3750
|
-
}
|
|
3751
|
-
|
|
3752
|
-
/**
|
|
3753
|
-
* `GET /cf/detect?path=` — 探测目录是 Pages 还是 Worker 项目。
|
|
3754
|
-
* @param {{path: string}} query
|
|
3755
|
-
* @returns {Promise<object>}
|
|
3756
|
-
*/
|
|
3757
|
-
async cloudflareDetect(query) {
|
|
3758
|
-
const dir = requireString(query, 'path', '目录路径');
|
|
3759
|
-
const kind = await detectProjectKind(dir);
|
|
3760
|
-
return { kind };
|
|
3761
|
-
}
|
|
3762
|
-
|
|
3763
|
-
/**
|
|
3764
|
-
* `POST /cf/deploy` — 一键部署 Pages 或 Worker。
|
|
3765
|
-
*
|
|
3766
|
-
* @param {object} body `{ path, kind?, project?, name?, branch?, environment? }`
|
|
3767
|
-
* @returns {Promise<object>}
|
|
3768
|
-
*/
|
|
3769
|
-
async cloudflareDeploy(body) {
|
|
3770
|
-
const dir = requireString(body, 'path', '目录路径');
|
|
3771
|
-
const { account, accountId } = await this.#cloudflareContext();
|
|
3772
|
-
const requestedKind = optionalString(body.kind);
|
|
3773
|
-
const detected = requestedKind ? { type: requestedKind, dir } : await detectProjectKind(dir);
|
|
3774
|
-
|
|
3775
|
-
if (!detected || (detected.type !== 'pages' && detected.type !== 'worker')) {
|
|
3776
|
-
throw httpError(
|
|
3777
|
-
400,
|
|
3778
|
-
'BAD_REQUEST',
|
|
3779
|
-
'这个目录既不是 Pages 静态产物(缺 dist/build/index.html),也不是 Worker 项目(缺 wrangler 配置)。'
|
|
3780
|
-
+ '请先构建前端产物,或初始化 wrangler.toml 后再部署。',
|
|
3781
|
-
);
|
|
3782
|
-
}
|
|
3783
|
-
|
|
3784
|
-
if (detected.type === 'pages') {
|
|
3785
|
-
const project = optionalString(body.project);
|
|
3786
|
-
if (!project) {
|
|
3787
|
-
throw httpError(400, 'BAD_REQUEST', '部署 Pages 需要指定项目名(project),或先在面板里选择/新建一个项目。');
|
|
3788
|
-
}
|
|
3789
|
-
const deployment = await createPagesDeployment(
|
|
3790
|
-
this.#cloudflareCredential(account),
|
|
3791
|
-
accountId,
|
|
3792
|
-
project,
|
|
3793
|
-
{ directory: detected.dir, branch: optionalString(body.branch) },
|
|
3794
|
-
);
|
|
3795
|
-
await this.#store.touchCloudflareAccount(account.id);
|
|
3796
|
-
return {
|
|
3797
|
-
kind: 'pages',
|
|
3798
|
-
project,
|
|
3799
|
-
deployment,
|
|
3800
|
-
dashUrl: dashUrl(accountId, `workers-and-pages/view/pages/${project}`),
|
|
3801
|
-
};
|
|
3802
|
-
}
|
|
3803
|
-
|
|
3804
|
-
const name = optionalString(body.name);
|
|
3805
|
-
if (!name) {
|
|
3806
|
-
throw httpError(400, 'BAD_REQUEST', '部署 Worker 需要指定 Worker 名(name)。');
|
|
3807
|
-
}
|
|
3808
|
-
const mainFile = await resolveWorkerMain(detected.dir);
|
|
3809
|
-
if (!mainFile) {
|
|
3810
|
-
throw httpError(400, 'BAD_REQUEST', '找不到 Worker 入口文件(wrangler 配置里的 main,或 src/index.js / index.js)。');
|
|
3811
|
-
}
|
|
3812
|
-
const { readFile } = await import('node:fs/promises');
|
|
3813
|
-
const { join } = await import('node:path');
|
|
3814
|
-
let bytes;
|
|
3815
|
-
try {
|
|
3816
|
-
bytes = await readFile(join(detected.dir, mainFile));
|
|
3817
|
-
} catch {
|
|
3818
|
-
throw httpError(400, 'BAD_REQUEST', `无法读取 Worker 入口文件 ${mainFile}。`);
|
|
3819
|
-
}
|
|
3820
|
-
const result = await deployWorkerModule(this.#cloudflareCredential(account), accountId, name, {
|
|
3821
|
-
mainFile,
|
|
3822
|
-
bytes,
|
|
3823
|
-
});
|
|
3824
|
-
await this.#store.touchCloudflareAccount(account.id);
|
|
3825
|
-
return {
|
|
3826
|
-
kind: 'worker',
|
|
3827
|
-
name,
|
|
3828
|
-
url: result.url,
|
|
3829
|
-
dashUrl: dashUrl(accountId, `workers/view/${name}`),
|
|
3830
|
-
};
|
|
3831
|
-
}
|
|
3832
|
-
|
|
3833
|
-
/**
|
|
3834
|
-
* `POST /cf/review` — 部署前审查(复用 review 引擎)。
|
|
3835
|
-
*
|
|
3836
|
-
* @param {object} body `{ path, kind?, presetIds?, customPrompt?, provider?, model?, reasoningEffort? }`
|
|
3837
|
-
* @returns {Promise<object>}
|
|
3838
|
-
*/
|
|
3839
|
-
async cloudflareReview(body) {
|
|
3840
|
-
const dir = requireString(body, 'path', '目录路径');
|
|
3841
|
-
const requestedKind = optionalString(body.kind);
|
|
3842
|
-
const detected = requestedKind ? { type: requestedKind, dir } : await detectProjectKind(dir);
|
|
3843
|
-
|
|
3844
|
-
const files = [];
|
|
3845
|
-
const chunks = [];
|
|
3846
|
-
let truncated = false;
|
|
3847
|
-
|
|
3848
|
-
if (detected && detected.type === 'pages') {
|
|
3849
|
-
const collected = await collectUploadFiles(detected.dir);
|
|
3850
|
-
if (collected.exceeded) truncated = true;
|
|
3851
|
-
for (const row of collected.files) {
|
|
3852
|
-
if (/(^|\/)node_modules\//.test(row.path)) continue;
|
|
3853
|
-
let text = '';
|
|
3854
|
-
try {
|
|
3855
|
-
text = row.bytes.toString('utf8');
|
|
3856
|
-
} catch { text = ''; }
|
|
3857
|
-
if (text.includes('\u0000')) continue;
|
|
3858
|
-
files.push({ path: row.path });
|
|
3859
|
-
if (text !== '') chunks.push({ path: row.path, text: text.slice(0, MAX_FILE_BYTES) });
|
|
3860
|
-
}
|
|
3861
|
-
} else if (detected && detected.type === 'worker') {
|
|
3862
|
-
const mainFile = await resolveWorkerMain(detected.dir);
|
|
3863
|
-
if (mainFile) {
|
|
3864
|
-
try {
|
|
3865
|
-
const { readFile } = await import('node:fs/promises');
|
|
3866
|
-
const { join } = await import('node:path');
|
|
3867
|
-
const text = (await readFile(join(detected.dir, mainFile))).toString('utf8');
|
|
3868
|
-
files.push({ path: mainFile });
|
|
3869
|
-
chunks.push({ path: mainFile, text: text.slice(0, MAX_FILE_BYTES) });
|
|
3870
|
-
} catch { /* 读不到就跳过 */ }
|
|
3871
|
-
}
|
|
3872
|
-
} else {
|
|
3873
|
-
return {
|
|
3874
|
-
reviewId: `cfreview_${Date.now().toString(36)}`,
|
|
3875
|
-
scope: 'cloudflare',
|
|
3876
|
-
files: [],
|
|
3877
|
-
findings: [],
|
|
3878
|
-
summary: '这个目录不是可部署的 Pages / Worker 项目,无需审查。',
|
|
3879
|
-
degraded: true,
|
|
3880
|
-
};
|
|
3881
|
-
}
|
|
3882
|
-
|
|
3883
|
-
const ruleFindings = [];
|
|
3884
|
-
for (const chunk of chunks) {
|
|
3885
|
-
ruleFindings.push(...scanSecrets(chunk.text, { file: chunk.path }));
|
|
3886
|
-
}
|
|
3887
|
-
for (const row of files) {
|
|
3888
|
-
if (/^\.env($|\.)/.test(row.path)) {
|
|
3889
|
-
ruleFindings.push(normalizeFinding({
|
|
3890
|
-
severity: 'blocker',
|
|
3891
|
-
category: 'secrets',
|
|
3892
|
-
title: '产物里包含环境变量文件',
|
|
3893
|
-
detail: '.env 会被上传到公开的 Pages 站点,等于公开密钥。请从产物中移除 .env*,改用环境变量注入。',
|
|
3894
|
-
file: row.path,
|
|
3895
|
-
}));
|
|
3896
|
-
}
|
|
3897
|
-
}
|
|
3898
|
-
|
|
3899
|
-
const presetIds = Array.isArray(body.presetIds)
|
|
3900
|
-
? body.presetIds.filter((id) => typeof id === 'string' && id !== '')
|
|
3901
|
-
: [];
|
|
3902
|
-
const stored = await this.#store.reviewPresets();
|
|
3903
|
-
const chosen = [
|
|
3904
|
-
...BUILTIN_PRESETS.filter((preset) => presetIds.includes(preset.id)),
|
|
3905
|
-
...stored.filter((preset) => presetIds.includes(preset.id)),
|
|
3906
|
-
];
|
|
3907
|
-
const customPrompt = optionalString(body.customPrompt) ?? '';
|
|
3908
|
-
const llm = this.#llm();
|
|
3909
|
-
let provider = optionalString(body.provider);
|
|
3910
|
-
let model = optionalString(body.model);
|
|
3911
|
-
if (llm && (!provider || !model)) {
|
|
3912
|
-
try {
|
|
3913
|
-
const fallback = await this.reviewModels();
|
|
3914
|
-
if (fallback.default) {
|
|
3915
|
-
provider = provider ?? fallback.default.provider;
|
|
3916
|
-
model = model ?? fallback.default.model;
|
|
3917
|
-
}
|
|
3918
|
-
} catch { /* 保留调用方给的值 */ }
|
|
3919
|
-
}
|
|
3920
|
-
|
|
3921
|
-
let modelFindings = [];
|
|
3922
|
-
let summary = '';
|
|
3923
|
-
let usage;
|
|
3924
|
-
let degraded = false;
|
|
3925
|
-
if (chunks.length === 0) {
|
|
3926
|
-
summary = '没有可审查的文本内容。';
|
|
3927
|
-
} else if (!llm) {
|
|
3928
|
-
degraded = true;
|
|
3929
|
-
summary = '宿主未提供 llm 服务,本次只执行了规则检查(敏感信息扫描)。';
|
|
3930
|
-
} else if (!provider || !model) {
|
|
3931
|
-
degraded = true;
|
|
3932
|
-
summary = '未找到可用的模型,本次只执行了规则检查(敏感信息扫描)。';
|
|
3933
|
-
} else {
|
|
3934
|
-
const instructions = [
|
|
3935
|
-
...chosen.map((preset) => `## ${preset.title}\n${preset.prompt}`),
|
|
3936
|
-
...(customPrompt ? [`## 用户补充要求\n${customPrompt}`] : []),
|
|
3937
|
-
].join('\n\n');
|
|
3938
|
-
const promptParts = [
|
|
3939
|
-
instructions,
|
|
3940
|
-
'## 审查范围',
|
|
3941
|
-
'这是即将部署到 Cloudflare 的文件内容(Pages 静态产物或 Worker 入口)。',
|
|
3942
|
-
`## 文件(${files.length} 个)`,
|
|
3943
|
-
files.map((row) => `- ${row.path}`).join('\n'),
|
|
3944
|
-
'## 内容',
|
|
3945
|
-
chunks.map((chunk) => `### ${chunk.path}\n\`\`\`\n${chunk.text}\n\`\`\``).join('\n\n'),
|
|
3946
|
-
].filter(Boolean);
|
|
3947
|
-
try {
|
|
3948
|
-
const result = await runModelReview(llm, {
|
|
3949
|
-
provider,
|
|
3950
|
-
model,
|
|
3951
|
-
reasoningEffort: optionalString(body.reasoningEffort),
|
|
3952
|
-
prompt: promptParts.join('\n\n'),
|
|
3953
|
-
});
|
|
3954
|
-
modelFindings = result.findings.map(normalizeFinding);
|
|
3955
|
-
summary = result.summary;
|
|
3956
|
-
usage = result.usage;
|
|
3957
|
-
} catch (error) {
|
|
3958
|
-
degraded = true;
|
|
3959
|
-
summary = `模型审查失败(${String(error && error.message ? error.message : error)}),本次只执行了规则检查。`;
|
|
3960
|
-
}
|
|
3961
|
-
}
|
|
3962
|
-
|
|
3963
|
-
const findings = sortFindings([...ruleFindings, ...modelFindings]);
|
|
3964
|
-
if (summary === '') {
|
|
3965
|
-
summary = findings.length === 0 ? '未发现明显问题。' : `共发现 ${findings.length} 处需要关注的问题。`;
|
|
3966
|
-
}
|
|
3967
|
-
return {
|
|
3968
|
-
reviewId: `cfreview_${Date.now().toString(36)}`,
|
|
3969
|
-
scope: 'cloudflare',
|
|
3970
|
-
kind: detected?.type ?? null,
|
|
3971
|
-
files,
|
|
3972
|
-
findings,
|
|
3973
|
-
summary,
|
|
3974
|
-
usage,
|
|
3975
|
-
degraded,
|
|
3976
|
-
truncated,
|
|
3977
|
-
};
|
|
3978
|
-
}
|
|
3979
|
-
|
|
3980
|
-
/**
|
|
3981
|
-
* The host `llm` service, when this composition has one.
|
|
3982
|
-
* @returns {object|undefined}
|
|
3983
|
-
*/
|
|
3984
|
-
#llm() {
|
|
3985
|
-
const ctx = this.ctx;
|
|
3986
|
-
if (!ctx) return undefined;
|
|
3987
|
-
try {
|
|
3988
|
-
return typeof ctx.get === 'function' ? ctx.get('llm') : ctx.llm;
|
|
3989
|
-
} catch {
|
|
3990
|
-
return undefined;
|
|
3991
|
-
}
|
|
3992
|
-
}
|
|
3993
|
-
|
|
3994
|
-
/* ---------------- lifecycle ---------------- */
|
|
3995
|
-
|
|
3996
|
-
/**
|
|
3997
|
-
* Boot: register routes and the agent tool, both bound to this fiber.
|
|
3998
|
-
* @returns {Promise<void>}
|
|
3999
|
-
*/
|
|
4000
|
-
async [ServiceClass.init || Symbol.for('cordis.init')]() {
|
|
4001
|
-
const ctx = this.ctx;
|
|
4002
|
-
const undo = [];
|
|
4003
|
-
try {
|
|
4004
|
-
const disposeRoutes = registerRoutes(ctx, this);
|
|
4005
|
-
if (disposeRoutes) undo.push(disposeRoutes);
|
|
4006
|
-
} catch (error) {
|
|
4007
|
-
// Never leave a half-mounted plugin: unwinding here keeps a failed
|
|
4008
|
-
// install from occupying routes that the retry then cannot take.
|
|
4009
|
-
for (const fn of undo) {
|
|
4010
|
-
try {
|
|
4011
|
-
fn();
|
|
4012
|
-
} catch {
|
|
4013
|
-
// best effort
|
|
4014
|
-
}
|
|
4015
|
-
}
|
|
4016
|
-
throw error;
|
|
4017
|
-
}
|
|
4018
|
-
this.#stop = () => {
|
|
4019
|
-
for (const fn of undo) {
|
|
4020
|
-
try {
|
|
4021
|
-
fn();
|
|
4022
|
-
} catch {
|
|
4023
|
-
// best effort
|
|
4024
|
-
}
|
|
4025
|
-
}
|
|
4026
|
-
};
|
|
4027
|
-
// cordis only unwinds effects registered through ctx.effect; a class
|
|
4028
|
-
// dispose() is not called on unload, so routes and the tool must be
|
|
4029
|
-
// installed as effects or an in-process reload leaks them — the next mount
|
|
4030
|
-
// would then die on webServer.register's duplicate-path throw.
|
|
4031
|
-
if (typeof ctx.effect === 'function') {
|
|
4032
|
-
ctx.effect(() => this.#stop, 'push: /api/push/* routes');
|
|
4033
|
-
}
|
|
4034
|
-
|
|
4035
|
-
// The agent tool lives in its own child fiber: `tools` is an OPTIONAL
|
|
4036
|
-
// service, and a composition that never publishes it must still serve the
|
|
4037
|
-
// panel. A nested inject also re-registers the tool if the tools service
|
|
4038
|
-
// is replaced (its provider restarting) without remounting the plugin.
|
|
4039
|
-
if (typeof ctx.inject === 'function') {
|
|
4040
|
-
ctx.inject(['tools'], (scoped) => {
|
|
4041
|
-
const disposeTool = registerTool(scoped, this);
|
|
4042
|
-
const disposeCfTool = registerCloudflareTool(scoped, this);
|
|
4043
|
-
const disposeAll = () => {
|
|
4044
|
-
try { if (typeof disposeCfTool === 'function') disposeCfTool(); } catch { /* gone */ }
|
|
4045
|
-
try { if (typeof disposeTool === 'function') disposeTool(); } catch { /* gone */ }
|
|
4046
|
-
};
|
|
4047
|
-
if (disposeTool || disposeCfTool) {
|
|
4048
|
-
if (typeof scoped.effect === 'function') {
|
|
4049
|
-
scoped.effect(() => disposeAll, 'push: github_link + cloudflare tools');
|
|
4050
|
-
} else {
|
|
4051
|
-
this.#stop = ((previous) => () => {
|
|
4052
|
-
try {
|
|
4053
|
-
disposeAll();
|
|
4054
|
-
} finally {
|
|
4055
|
-
previous();
|
|
4056
|
-
}
|
|
4057
|
-
})(this.#stop);
|
|
4058
|
-
}
|
|
4059
|
-
}
|
|
4060
|
-
});
|
|
4061
|
-
}
|
|
4062
|
-
}
|
|
4063
|
-
|
|
4064
|
-
/** Idempotent teardown (also reached through the effect above). */
|
|
4065
|
-
dispose() {
|
|
4066
|
-
this.#stop();
|
|
4067
|
-
this.#stop = () => {};
|
|
4068
|
-
}
|
|
4069
|
-
}
|
|
4070
|
-
|
|
4071
|
-
/* ------------------------------------------------------------------ */
|
|
4072
|
-
/* Route table */
|
|
4073
|
-
/* ------------------------------------------------------------------ */
|
|
4074
|
-
|
|
4075
|
-
/**
|
|
4076
|
-
* Build the route table: one entry per (path, method).
|
|
4077
|
-
*
|
|
4078
|
-
* The paths are literal contract paths, so a typo is a contract violation that
|
|
4079
|
-
* shows up immediately in the panel — there is no dynamic segment anywhere.
|
|
4080
|
-
*
|
|
4081
|
-
* @param {GithubLinkHost} host
|
|
4082
|
-
* @returns {{path: string, method: string, run: (ctx: object) => Promise<any>}[]}
|
|
4083
|
-
*/
|
|
4084
|
-
function buildRoutes(host) {
|
|
4085
|
-
/** GET route. */
|
|
4086
|
-
const get = (path, run) => ({ path, method: 'GET', run });
|
|
4087
|
-
/** POST route. */
|
|
4088
|
-
const post = (path, run) => ({ path, method: 'POST', run });
|
|
4089
|
-
|
|
4090
|
-
return [
|
|
4091
|
-
// §1 accounts + settings
|
|
4092
|
-
get('/state', async () => ({ data: await host.state() })),
|
|
4093
|
-
get('/npm/accounts', async () => ({ data: await host.npmAccounts() })),
|
|
4094
|
-
post('/npm/account', async ({ body }) => ({ data: await host.npmAccountAdd(body) })),
|
|
4095
|
-
post('/npm/account/remove', async ({ body }) => ({ data: await host.npmAccountRemove(body) })),
|
|
4096
|
-
post('/npm/account/active', async ({ body }) => ({ data: await host.npmAccountActive(body) })),
|
|
4097
|
-
get('/npm/packages', async ({ query }) => ({
|
|
4098
|
-
data: await host.npmPackages({ size: Number(query('size')) || undefined, from: Number(query('from')) || 0 }),
|
|
4099
|
-
})),
|
|
4100
|
-
get('/npm/package', async ({ query }) => ({ data: await host.npmPackage({ name: query('name') }) })),
|
|
4101
|
-
get('/npm/search', async ({ query }) => ({
|
|
4102
|
-
data: await host.npmSearch({
|
|
4103
|
-
q: query('q'),
|
|
4104
|
-
size: Number(query('size')) || undefined,
|
|
4105
|
-
}),
|
|
4106
|
-
})),
|
|
4107
|
-
post('/npm/init', async ({ body }) => ({ data: await host.npmInit(body) })),
|
|
4108
|
-
get('/npm/pack', async ({ query }) => ({ data: await host.npmPackInspect({ path: query('path') }) })),
|
|
4109
|
-
post('/npm/pack', async ({ body }) => ({ data: await host.npmPack(body) })),
|
|
4110
|
-
post('/npm/publish', async ({ body }) => ({ data: await host.npmPublish(body) })),
|
|
4111
|
-
post('/npm/review/run', async ({ body }) => ({ data: await host.npmPublishReview(body) })),
|
|
4112
|
-
get('/npm/preflight', async ({ query }) => ({
|
|
4113
|
-
data: await host.npmPreflight({ path: query('path') }),
|
|
4114
|
-
})),
|
|
4115
|
-
get('/npm/deps', async ({ query }) => ({
|
|
4116
|
-
data: await host.npmProjectDeps({ path: query('path') }),
|
|
4117
|
-
})),
|
|
4118
|
-
// §6 Cloudflare:账号、概览、Pages、Workers、Zones、部署与审查
|
|
4119
|
-
get('/cf/accounts', async () => ({ data: await host.cloudflareAccounts() })),
|
|
4120
|
-
post('/cf/account', async ({ body }) => ({ data: await host.cloudflareAccountAdd(body) })),
|
|
4121
|
-
post('/cf/account/remove', async ({ body }) => ({ data: await host.cloudflareAccountRemove(body) })),
|
|
4122
|
-
post('/cf/account/active', async ({ body }) => ({ data: await host.cloudflareAccountActive(body) })),
|
|
4123
|
-
post('/cf/account/select', async ({ body }) => ({ data: await host.cloudflareAccountSelect(body) })),
|
|
4124
|
-
get('/cf/accounts/list', async () => ({ data: await host.cloudflareAccountList() })),
|
|
4125
|
-
get('/cf/overview', async () => ({ data: await host.cloudflareOverview() })),
|
|
4126
|
-
get('/cf/projects', async () => ({ data: await host.cloudflareProjects() })),
|
|
4127
|
-
post('/cf/projects/create', async ({ body }) => ({ data: await host.cloudflareProjectCreate(body) })),
|
|
4128
|
-
post('/cf/projects/delete', async ({ body }) => ({ data: await host.cloudflareProjectDelete(body) })),
|
|
4129
|
-
get('/cf/workers', async () => ({ data: await host.cloudflareWorkers() })),
|
|
4130
|
-
post('/cf/workers/delete', async ({ body }) => ({ data: await host.cloudflareWorkerDelete(body) })),
|
|
4131
|
-
get('/cf/zones', async () => ({ data: await host.cloudflareZones() })),
|
|
4132
|
-
get('/cf/detect', async ({ query }) => ({ data: await host.cloudflareDetect({ path: query('path') }) })),
|
|
4133
|
-
post('/cf/deploy', async ({ body }) => ({ data: await host.cloudflareDeploy(body) })),
|
|
4134
|
-
post('/cf/review', async ({ body }) => ({ data: await host.cloudflareReview(body) })),
|
|
4135
|
-
get('/diagnostics', async () => ({ data: await host.diagnostics() })),
|
|
4136
|
-
post('/accounts/token', async ({ body }) => ({ data: await host.addTokenAccount(body) })),
|
|
4137
|
-
post('/accounts/device/start', async () => ({ data: await host.deviceStart() })),
|
|
4138
|
-
post('/accounts/device/poll', async ({ body }) => ({ data: await host.devicePoll(body) })),
|
|
4139
|
-
post('/accounts/activate', async ({ body }) => ({ data: await host.activateAccount(body) })),
|
|
4140
|
-
post('/accounts/remove', async ({ body }) => ({ data: await host.removeAccount(body) })),
|
|
4141
|
-
post('/settings', async ({ body }) => ({ data: await host.updateSettings(body) })),
|
|
4142
|
-
|
|
4143
|
-
// §2 remote repositories
|
|
4144
|
-
get('/repos', async ({ query }) => ({
|
|
4145
|
-
data: await host.repos({
|
|
4146
|
-
page: query('page'),
|
|
4147
|
-
q: query('q'),
|
|
4148
|
-
affiliation: query('affiliation'),
|
|
4149
|
-
sort: query('sort'),
|
|
4150
|
-
}),
|
|
4151
|
-
})),
|
|
4152
|
-
get('/repos/detail', async ({ query }) => ({ data: await host.repoDetail({ owner: query('owner'), name: query('name') }) })),
|
|
4153
|
-
post('/repos/create', async ({ body }) => ({ data: await host.repoCreate(body) })),
|
|
4154
|
-
post('/repos/delete', async ({ body }) => ({ data: await host.repoDelete(body) })),
|
|
4155
|
-
|
|
4156
|
-
// §3c repository management — the aggregate read, then the writes. The
|
|
4157
|
-
// rename/transfer routes answer CONFLICT without `confirm: true`, exactly
|
|
4158
|
-
// like the destructive local-git routes below.
|
|
4159
|
-
get('/repos/languages', async ({ query }) => ({
|
|
4160
|
-
data: await host.repoLanguages({ owner: query('owner'), name: query('name') }),
|
|
4161
|
-
})),
|
|
4162
|
-
post('/releases/asset', async ({ body }) => ({ data: await host.releaseAssetUpload(body) })),
|
|
4163
|
-
post('/releases/asset/delete', async ({ body }) => ({ data: await host.releaseAssetDelete(body) })),
|
|
4164
|
-
get('/repos/manage', async ({ query }) => ({
|
|
4165
|
-
data: await host.repoManage({ owner: query('owner'), name: query('name') }),
|
|
4166
|
-
})),
|
|
4167
|
-
post('/repos/update', async ({ body }) => ({ data: await host.repoUpdate(body) })),
|
|
4168
|
-
post('/repos/branch/rename', async ({ body }) => ({ data: await host.repoBranchRename(body) })),
|
|
4169
|
-
post('/repos/branch/delete', async ({ body }) => ({ data: await host.repoBranchDelete(body) })),
|
|
4170
|
-
post('/repos/branch/protect', async ({ body }) => ({ data: await host.repoBranchProtect(body) })),
|
|
4171
|
-
post('/repos/release/delete', async ({ body }) => ({ data: await host.repoReleaseDelete(body) })),
|
|
4172
|
-
post('/repos/release/update', async ({ body }) => ({ data: await host.repoReleaseUpdate(body) })),
|
|
4173
|
-
post('/repos/collaborator/add', async ({ body }) => ({ data: await host.repoCollaboratorAdd(body) })),
|
|
4174
|
-
post('/repos/collaborator/remove', async ({ body }) => ({ data: await host.repoCollaboratorRemove(body) })),
|
|
4175
|
-
post('/repos/rename', async ({ body }) => ({ data: await host.repoRename(body) })),
|
|
4176
|
-
post('/repos/transfer', async ({ body }) => ({ data: await host.repoTransfer(body) })),
|
|
4177
|
-
|
|
4178
|
-
// `/releases` carries BOTH a read and a write (CONTRACT §2), so the method
|
|
4179
|
-
// decides which one runs — webServer allows a single handler per path.
|
|
4180
|
-
get('/releases', async ({ query }) => ({ data: await host.releases({ owner: query('owner'), repo: query('repo') }) })),
|
|
4181
|
-
post('/releases', async ({ body }) => ({ data: await host.releaseCreate(body) })),
|
|
4182
|
-
|
|
4183
|
-
// §2 activity: contribution calendar (GraphQL) + notifications ("最近消息")
|
|
4184
|
-
get('/contributions', async ({ query }) => ({
|
|
4185
|
-
data: await host.contributions({ login: query('login'), days: query('days') }),
|
|
4186
|
-
})),
|
|
4187
|
-
get('/notifications', async ({ query }) => ({
|
|
4188
|
-
data: await host.notifications({ all: query('all'), limit: query('limit') }),
|
|
4189
|
-
})),
|
|
4190
|
-
post('/notifications/read', async ({ body }) => ({ data: await host.notificationRead(body) })),
|
|
4191
|
-
|
|
4192
|
-
// §3 local repository — reads
|
|
4193
|
-
get('/local/status', async ({ query }) => ({ data: await host.localStatus(query('path')) })),
|
|
4194
|
-
get('/local/log', async ({ query }) => ({
|
|
4195
|
-
data: await host.localLog({ path: query('path'), limit: query('limit'), ref: query('ref') }),
|
|
4196
|
-
})),
|
|
4197
|
-
get('/local/diff', async ({ query }) => ({
|
|
4198
|
-
data: await host.localDiff({ path: query('path'), file: query('file'), staged: query('staged') }),
|
|
4199
|
-
})),
|
|
4200
|
-
get('/local/remotes', async ({ query }) => ({ data: await host.localRemotes({ path: query('path') }) })),
|
|
4201
|
-
// `/local/commit` is a READ with ?sha= and a WRITE with a body (CONTRACT §3).
|
|
4202
|
-
get('/local/commit', async ({ query }) => ({
|
|
4203
|
-
data: await host.localCommitDetail({ path: query('path'), sha: query('sha') }),
|
|
4204
|
-
})),
|
|
4205
|
-
|
|
4206
|
-
// §3 local repository — writes
|
|
4207
|
-
post('/local/init', async ({ body }) => ({ data: await host.localInit(body) })),
|
|
4208
|
-
post('/local/remote', async ({ body }) => ({ data: await host.localSetRemote(body) })),
|
|
4209
|
-
post('/local/fetch', async ({ body }) => ({ data: await host.localFetch(body) })),
|
|
4210
|
-
post('/local/pull', async ({ body }) => ({ data: await host.localPull(body) })),
|
|
4211
|
-
post('/local/push', async ({ body }) => ({ data: await host.localPush(body) })),
|
|
4212
|
-
post('/local/commit', async ({ body }) => ({ data: await host.localCommit(body) })),
|
|
4213
|
-
post('/local/checkout', async ({ body }) => ({ data: await host.localCheckout(body) })),
|
|
4214
|
-
post('/local/branch', async ({ body }) => ({ data: await host.localBranch(body) })),
|
|
4215
|
-
post('/local/branch/delete', async ({ body }) => ({ data: await host.localBranchDelete(body) })),
|
|
4216
|
-
post('/local/merge', async ({ body }) => ({ data: await host.localMerge(body) })),
|
|
4217
|
-
post('/local/reset', async ({ body }) => ({ data: await host.localReset(body) })),
|
|
4218
|
-
post('/local/revert', async ({ body }) => ({ data: await host.localRevert(body) })),
|
|
4219
|
-
post('/local/revert-commit', async ({ body }) => ({ data: await host.localRevert(body) })),
|
|
4220
|
-
post('/local/tag', async ({ body }) => ({ data: await host.localTag(body) })),
|
|
4221
|
-
post('/local/stash', async ({ body }) => ({ data: await host.localStash(body) })),
|
|
4222
|
-
post('/local/stash/pop', async ({ body }) => ({ data: await host.localStashPop(body) })),
|
|
4223
|
-
post('/local/restore', async ({ body }) => ({ data: await host.localRestore(body) })),
|
|
4224
|
-
post('/local/discard-all', async ({ body }) => ({ data: await host.localDiscardAll(body) })),
|
|
4225
|
-
|
|
4226
|
-
// §3d pre-push review
|
|
4227
|
-
get('/review/presets', async () => ({ data: await host.reviewPresets() })),
|
|
4228
|
-
post('/review/presets', async ({ body }) => ({ data: await host.reviewPresetSave(body) })),
|
|
4229
|
-
post('/review/presets/delete', async ({ body }) => ({ data: await host.reviewPresetDelete(body) })),
|
|
4230
|
-
get('/review/models', async () => ({ data: await host.reviewModels() })),
|
|
4231
|
-
get('/review/pending', async () => ({ data: await host.reviewPending() })),
|
|
4232
|
-
post('/review/pending/clear', async ({ body }) => ({ data: await host.reviewPendingClear(body) })),
|
|
4233
|
-
post('/review/run', async ({ body }) => ({ data: await host.reviewRun(body) })),
|
|
4234
|
-
post('/review/project', async ({ body }) => ({ data: await host.reviewProject(body) })),
|
|
4235
|
-
|
|
4236
|
-
// §3b push targets + per-branch memory
|
|
4237
|
-
get('/push/targets', async ({ query }) => ({ data: await host.pushTargets({ path: query('path') }) })),
|
|
4238
|
-
get('/push/remotes', async ({ query }) => ({
|
|
4239
|
-
data: await host.pushRemotes({ q: query('q'), page: query('page') }),
|
|
4240
|
-
})),
|
|
4241
|
-
get('/push/memory', async ({ query }) => ({ data: await host.pushMemory({ path: query('path') }) })),
|
|
4242
|
-
// Optional companion to `/local/push` (see the service method): forget one
|
|
4243
|
-
// branch's remembered target so a wrong one is not permanent.
|
|
4244
|
-
post('/local/push/target/forget', async ({ body }) => ({ data: await host.localForgetPushTarget(body) })),
|
|
4245
|
-
];
|
|
4246
|
-
}
|
|
4247
|
-
|
|
4248
|
-
/**
|
|
4249
|
-
* Register every route on the `webServer` service.
|
|
4250
|
-
*
|
|
4251
|
-
* Handlers are grouped by PATH because one path may serve both a GET and a
|
|
4252
|
-
* POST; the group dispatches on `req.method` and answers 405 for anything else.
|
|
4253
|
-
*
|
|
4254
|
-
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
4255
|
-
* @param {GithubLinkHost} host
|
|
4256
|
-
* @returns {(() => void)|null} disposer, or null without a webServer.
|
|
4257
|
-
*/
|
|
4258
|
-
function registerRoutes(ctx, host) {
|
|
4259
|
-
const webServer = ctx.webServer;
|
|
4260
|
-
if (!webServer || typeof webServer.register !== 'function') return null;
|
|
4261
|
-
|
|
4262
|
-
const byPath = new Map();
|
|
4263
|
-
for (const route of buildRoutes(host)) {
|
|
4264
|
-
const full = `${ROUTE_PREFIX}${route.path}`;
|
|
4265
|
-
const existing = byPath.get(full);
|
|
4266
|
-
if (existing) existing[route.method] = route.run;
|
|
4267
|
-
else byPath.set(full, { [route.method]: route.run });
|
|
4268
|
-
}
|
|
4269
|
-
|
|
4270
|
-
const disposers = [];
|
|
4271
|
-
for (const [path, methods] of byPath) {
|
|
4272
|
-
const handler = async (req, res) => {
|
|
4273
|
-
// The token list is read ONCE per request, before anything can fail, so
|
|
4274
|
-
// the error path can scrub messages synchronously. A failed read leaves
|
|
4275
|
-
// an empty list: the pattern-based redaction in store.js still masks
|
|
4276
|
-
// recognizable GitHub token shapes.
|
|
4277
|
-
let secrets = [];
|
|
4278
|
-
try {
|
|
4279
|
-
secrets = await host.store.secrets();
|
|
4280
|
-
} catch {
|
|
4281
|
-
secrets = [];
|
|
4282
|
-
}
|
|
4283
|
-
try {
|
|
4284
|
-
// CSRF guard: a non-GET request must carry the plugin header. A custom
|
|
4285
|
-
// header cannot be set cross-origin without a preflight this server
|
|
4286
|
-
// never answers, so it proves same-origin intent.
|
|
4287
|
-
if (req.method !== 'GET' && req.headers[PLUGIN_HEADER] !== PLUGIN_HEADER_VALUE) {
|
|
4288
|
-
throw httpError(403, 'FORBIDDEN', `缺少请求头 ${PLUGIN_HEADER}: ${PLUGIN_HEADER_VALUE}`);
|
|
4289
|
-
}
|
|
4290
|
-
const run = methods[req.method];
|
|
4291
|
-
if (typeof run !== 'function') {
|
|
4292
|
-
throw httpError(405, 'BAD_REQUEST', `该路径不支持 ${req.method} 方法`);
|
|
4293
|
-
}
|
|
4294
|
-
const body = req.method === 'GET' ? {} : await readBody(req);
|
|
4295
|
-
const result = await run({ body, query: queryOf(req), req });
|
|
4296
|
-
sendOk(res, result.data);
|
|
4297
|
-
} catch (error) {
|
|
4298
|
-
sendError(res, toWireError(error, (text) => redactSecrets(text, secrets)));
|
|
4299
|
-
}
|
|
4300
|
-
};
|
|
4301
|
-
try {
|
|
4302
|
-
disposers.push(webServer.register({ kind: 'exact', path, handler }));
|
|
4303
|
-
} catch (error) {
|
|
4304
|
-
// A leaked route from a previous instance only clears on a profile
|
|
4305
|
-
// restart, so say that instead of surfacing a bare duplicate error.
|
|
4306
|
-
throw new Error(
|
|
4307
|
-
`dsh-push: 无法注册路由 ${path}:${error?.message ?? error}`
|
|
4308
|
-
+ '(可能是上一次加载残留的路由;重启 DSH 后重试)',
|
|
4309
|
-
{ cause: error },
|
|
4310
|
-
);
|
|
4311
|
-
}
|
|
4312
|
-
}
|
|
4313
|
-
|
|
4314
|
-
return () => {
|
|
4315
|
-
for (const dispose of disposers) {
|
|
4316
|
-
try {
|
|
4317
|
-
dispose();
|
|
4318
|
-
} catch {
|
|
4319
|
-
// best effort
|
|
4320
|
-
}
|
|
4321
|
-
}
|
|
4322
|
-
};
|
|
4323
|
-
}
|
|
4324
|
-
|
|
4325
|
-
/* ------------------------------------------------------------------ */
|
|
4326
|
-
/* Agent tool */
|
|
4327
|
-
/* ------------------------------------------------------------------ */
|
|
4328
|
-
|
|
4329
|
-
/** The `github_link` tool's parameter schema (plain JSON Schema). */
|
|
4330
|
-
const TOOL_PARAMETERS = {
|
|
4331
|
-
type: 'object',
|
|
4332
|
-
properties: {
|
|
4333
|
-
action: {
|
|
4334
|
-
type: 'string',
|
|
4335
|
-
enum: ['status', 'log', 'push', 'pull', 'commit', 'repos', 'accounts', 'create_repo', 'release', 'review'],
|
|
4336
|
-
description: '要执行的操作:status(本地仓库状态)、log(提交图)、push(推送)、pull(拉取)、commit(提交)、repos(远端仓库列表)、accounts(已登录账号)。',
|
|
4337
|
-
},
|
|
4338
|
-
path: {
|
|
4339
|
-
type: 'string',
|
|
4340
|
-
description: '本地仓库目录的绝对路径;省略时使用当前会话的工作目录。',
|
|
4341
|
-
},
|
|
4342
|
-
message: {
|
|
4343
|
-
type: 'string',
|
|
4344
|
-
description: 'commit 时必填:提交信息。',
|
|
4345
|
-
},
|
|
4346
|
-
remote: {
|
|
4347
|
-
type: 'string',
|
|
4348
|
-
description: '远端名称,默认 origin。',
|
|
4349
|
-
},
|
|
4350
|
-
branch: {
|
|
4351
|
-
type: 'string',
|
|
4352
|
-
description: 'push/pull 时可指定分支名;省略则使用当前分支。',
|
|
4353
|
-
},
|
|
4354
|
-
limit: {
|
|
4355
|
-
type: 'number',
|
|
4356
|
-
description: 'log 返回的提交条数,默认 60,最大 500。',
|
|
4357
|
-
},
|
|
4358
|
-
force: {
|
|
4359
|
-
type: 'boolean',
|
|
4360
|
-
description: 'push 时强制推送(使用 --force-with-lease,不会覆盖他人提交)。',
|
|
4361
|
-
},
|
|
4362
|
-
q: {
|
|
4363
|
-
type: 'string',
|
|
4364
|
-
description: 'repos 时的搜索关键词,留空则列出全部仓库。',
|
|
4365
|
-
},
|
|
4366
|
-
page: {
|
|
4367
|
-
type: 'number',
|
|
4368
|
-
description: 'repos 的页码,从 1 开始。',
|
|
4369
|
-
},
|
|
4370
|
-
repoName: {
|
|
4371
|
-
type: 'string',
|
|
4372
|
-
description: 'create_repo 时的仓库名;release 时省略则用当前工作区的远端仓库。',
|
|
4373
|
-
},
|
|
4374
|
-
owner: {
|
|
4375
|
-
type: 'string',
|
|
4376
|
-
description: 'push/release 的目标仓库所有者;与 repo 一起使用时替代本地远端。',
|
|
4377
|
-
},
|
|
4378
|
-
repo: {
|
|
4379
|
-
type: 'string',
|
|
4380
|
-
description: 'push/release 的目标仓库名。',
|
|
4381
|
-
},
|
|
4382
|
-
description: {
|
|
4383
|
-
type: 'string',
|
|
4384
|
-
description: 'create_repo 时的仓库简介。',
|
|
4385
|
-
},
|
|
4386
|
-
isPrivate: {
|
|
4387
|
-
type: 'boolean',
|
|
4388
|
-
description: 'create_repo 时是否创建为私有仓库,默认 true。',
|
|
4389
|
-
},
|
|
4390
|
-
autoInit: {
|
|
4391
|
-
type: 'boolean',
|
|
4392
|
-
description: 'create_repo 时是否带一个初始 README 提交(有提交才能打标签或发布),默认 false。',
|
|
4393
|
-
},
|
|
4394
|
-
tagName: {
|
|
4395
|
-
type: 'string',
|
|
4396
|
-
description: 'release 时的标签名,例如 v1.2.0;不存在会被创建。',
|
|
4397
|
-
},
|
|
4398
|
-
releaseName: {
|
|
4399
|
-
type: 'string',
|
|
4400
|
-
description: 'release 的标题,默认与标签名相同。',
|
|
4401
|
-
},
|
|
4402
|
-
releaseBody: {
|
|
4403
|
-
type: 'string',
|
|
4404
|
-
description: 'release 的说明文字。',
|
|
4405
|
-
},
|
|
4406
|
-
draft: {
|
|
4407
|
-
type: 'boolean',
|
|
4408
|
-
description: 'release 时是否存为草稿。',
|
|
4409
|
-
},
|
|
4410
|
-
presetIds: {
|
|
4411
|
-
type: 'array',
|
|
4412
|
-
items: { type: 'string' },
|
|
4413
|
-
description: 'review 时要使用的内置审查项 id,例如 builtin_secrets_token。',
|
|
4414
|
-
},
|
|
4415
|
-
customPrompt: {
|
|
4416
|
-
type: 'string',
|
|
4417
|
-
description: 'review 时的额外审查要求。',
|
|
4418
|
-
},
|
|
4419
|
-
},
|
|
4420
|
-
required: ['action'],
|
|
4421
|
-
};
|
|
4422
|
-
|
|
4423
|
-
/** The tool's output schema: one object covering every action's payload. */
|
|
4424
|
-
const TOOL_OUTPUT_SCHEMA = {
|
|
4425
|
-
type: 'object',
|
|
4426
|
-
additionalProperties: true,
|
|
4427
|
-
properties: {
|
|
4428
|
-
action: { type: 'string' },
|
|
4429
|
-
output: { type: 'string' },
|
|
4430
|
-
status: { type: 'object', additionalProperties: true },
|
|
4431
|
-
commits: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
4432
|
-
hasMore: { type: 'boolean' },
|
|
4433
|
-
page: { type: 'number' },
|
|
4434
|
-
repos: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
4435
|
-
accounts: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
4436
|
-
// `activeAccountId` is nullable, and this host's schema subset can express
|
|
4437
|
-
// neither `type: [...]` nor `anyOf`. Declaring it would reject the whole
|
|
4438
|
-
// registration, so it is left to `additionalProperties: true` above — the
|
|
4439
|
-
// value still carries the field; the schema just does not describe it.
|
|
4440
|
-
},
|
|
4441
|
-
};
|
|
4442
|
-
|
|
4443
|
-
/**
|
|
4444
|
-
* Render one tool result as the single text block the model reads.
|
|
4445
|
-
* @param {object} value the canonical output value.
|
|
4446
|
-
* @returns {string}
|
|
4447
|
-
*/
|
|
4448
|
-
function renderToolResult(value) {
|
|
4449
|
-
const action = String(value?.action ?? '');
|
|
4450
|
-
if (typeof value?.output === 'string') return `【${action}】\n${value.output}`;
|
|
4451
|
-
if (action === 'status') {
|
|
4452
|
-
const status = value.status ?? {};
|
|
4453
|
-
if (!status.isRepo) return `【status】${status.root ?? '当前目录'} 不是 Git 仓库。`;
|
|
4454
|
-
const dirty = status.dirty ?? {};
|
|
4455
|
-
const lines = [
|
|
4456
|
-
`【status】${status.root}`,
|
|
4457
|
-
`分支:${status.detachedHead ? '(分离 HEAD)' : (status.branch ?? '(未知)')}`
|
|
4458
|
-
+ ` 上游:${status.upstream ?? '未设置'}`
|
|
4459
|
-
+ ` 领先 ${status.ahead} / 落后 ${status.behind}`,
|
|
4460
|
-
`改动:已暂存 ${dirty.staged},未暂存/已修改 ${dirty.changed},未跟踪 ${dirty.untracked},冲突 ${dirty.conflicted}`,
|
|
4461
|
-
];
|
|
4462
|
-
if (status.files?.length) {
|
|
4463
|
-
lines.push('文件:');
|
|
4464
|
-
for (const file of status.files.slice(0, 40)) {
|
|
4465
|
-
lines.push(` ${file.index}${file.worktree} ${file.path}${file.untracked ? '(未跟踪)' : ''}`);
|
|
4466
|
-
}
|
|
4467
|
-
if (status.files.length > 40) lines.push(` …共 ${status.files.length} 个`);
|
|
4468
|
-
}
|
|
4469
|
-
return lines.join('\n');
|
|
4470
|
-
}
|
|
4471
|
-
if (action === 'log') {
|
|
4472
|
-
const commits = value.commits ?? [];
|
|
4473
|
-
if (commits.length === 0) return '【log】没有提交记录。';
|
|
4474
|
-
return ['【log】最近提交(lane 为图列号):']
|
|
4475
|
-
.concat(commits.map((commit) => ` ${String(commit.lane).padStart(2, ' ')} ${commit.shortSha} ${commit.subject}`))
|
|
4476
|
-
.join('\n');
|
|
4477
|
-
}
|
|
4478
|
-
if (action === 'repos') {
|
|
4479
|
-
const repos = value.repos ?? [];
|
|
4480
|
-
if (repos.length === 0) return '【repos】没有匹配的仓库。';
|
|
4481
|
-
return [`【repos】第 ${value.page ?? 1} 页${value.hasMore ? '(还有更多)' : ''}:`]
|
|
4482
|
-
.concat(repos.map((repo) => ` ${repo.fullName}${repo.private ? '(私有)' : ''} · 默认分支 ${repo.defaultBranch}`))
|
|
4483
|
-
.join('\n');
|
|
4484
|
-
}
|
|
4485
|
-
if (action === 'accounts') {
|
|
4486
|
-
const accounts = value.accounts ?? [];
|
|
4487
|
-
if (accounts.length === 0) return '【accounts】还没有登录任何 GitHub 账号。';
|
|
4488
|
-
return ['【accounts】']
|
|
4489
|
-
.concat(accounts.map((account) => ` ${account.login}${account.id === value.activeAccountId ? '(当前)' : ''} · ${account.tokenKind} · [${account.scopes.join(', ')}]`))
|
|
4490
|
-
.join('\n');
|
|
4491
|
-
}
|
|
4492
|
-
return JSON.stringify(value);
|
|
4493
|
-
}
|
|
4494
|
-
|
|
4495
|
-
/**
|
|
4496
|
-
* Register the `github_link` agent tool.
|
|
4497
|
-
*
|
|
4498
|
-
* Registration is best-effort: a host composition without the tools service
|
|
4499
|
-
* still serves the HTTP API, so a missing `register` returns null instead of
|
|
4500
|
-
* failing the mount.
|
|
4501
|
-
*
|
|
4502
|
-
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
4503
|
-
* @param {GithubLinkHost} host
|
|
4504
|
-
* @returns {(() => void)|null} disposer, or null when no tools service exists.
|
|
4505
|
-
*/
|
|
4506
|
-
/**
|
|
4507
|
-
* The last agent-tool registration outcome, for GET /diagnostics.
|
|
4508
|
-
*
|
|
4509
|
-
* `{ attempted, registered, visible, error }` — `visible` is probed live from
|
|
4510
|
-
* the tools service, so it also catches a registration that succeeded and was
|
|
4511
|
-
* later removed (a reload, a scope restriction).
|
|
4512
|
-
*/
|
|
4513
|
-
let toolRegistration = { attempted: false, registered: false, error: null };
|
|
4514
|
-
|
|
4515
|
-
function registerTool(ctx, host) {
|
|
4516
|
-
const tools = typeof ctx.get === 'function' ? ctx.get('tools') : ctx.tools;
|
|
4517
|
-
if (!tools || typeof tools.register !== 'function') return null;
|
|
4518
|
-
|
|
4519
|
-
const definition = {
|
|
4520
|
-
name: 'github_link',
|
|
4521
|
-
description:
|
|
4522
|
-
'操作当前工作区的 GitHub / Git 仓库:查看本地状态(分支、ahead/behind、文件改动)、查看提交图(带 lane 图列)、推送、拉取、提交,以及列出当前账号的 GitHub 远端仓库和已登录账号。'
|
|
4523
|
-
+ '默认作用于当前会话的工作目录;需要别的目录时传绝对路径 path。所有输出为中文文本。'
|
|
4524
|
-
+ '推送/拉取会自动使用插件里已登录的当前账号令牌,令牌不会写进仓库配置。',
|
|
4525
|
-
parameters: TOOL_PARAMETERS,
|
|
4526
|
-
output: {
|
|
4527
|
-
schema: TOOL_OUTPUT_SCHEMA,
|
|
4528
|
-
render: (_args, value) => [{ type: 'text', text: renderToolResult(value) }],
|
|
4529
|
-
},
|
|
4530
|
-
timeoutMs: 200_000,
|
|
4531
|
-
isConcurrencySafe: () => false,
|
|
4532
|
-
async execute(args, exec) {
|
|
4533
|
-
exec?.signal?.throwIfAborted?.();
|
|
4534
|
-
const sessionCwd = exec?.agent?.session?.header?.cwd
|
|
4535
|
-
?? exec?.agent?.session?.cwd
|
|
4536
|
-
?? undefined;
|
|
4537
|
-
try {
|
|
4538
|
-
return await host.toolCall(args ?? {}, {
|
|
4539
|
-
resolvePath: async () => (typeof sessionCwd === 'string' ? sessionCwd : process.cwd()),
|
|
4540
|
-
});
|
|
4541
|
-
} catch (error) {
|
|
4542
|
-
const wire = toWireError(error, (text) => redactSecrets(text));
|
|
4543
|
-
// The tool surface has no error envelope: the model sees the message,
|
|
4544
|
-
// and the code is kept in front so it can react to NO_ACCOUNT etc.
|
|
4545
|
-
throw new Error(`[${wire.code}] ${wire.message}`);
|
|
4546
|
-
}
|
|
4547
|
-
},
|
|
4548
|
-
};
|
|
4549
|
-
|
|
4550
|
-
try {
|
|
4551
|
-
const dispose = tools.register(definition);
|
|
4552
|
-
toolRegistration = { attempted: true, registered: true, error: null };
|
|
4553
|
-
return () => {
|
|
4554
|
-
toolRegistration = { attempted: true, registered: false, error: null };
|
|
4555
|
-
if (typeof dispose === 'function') dispose();
|
|
4556
|
-
};
|
|
4557
|
-
} catch (error) {
|
|
4558
|
-
// A name collision with another plugin must not take the HTTP API down,
|
|
4559
|
-
// but it must not be invisible either: /diagnostics reports it.
|
|
4560
|
-
toolRegistration = {
|
|
4561
|
-
attempted: true,
|
|
4562
|
-
registered: false,
|
|
4563
|
-
error: String(error && error.message ? error.message : error),
|
|
4564
|
-
};
|
|
4565
|
-
console?.warn?.(`dsh-push: github_link 工具注册失败:${error?.message ?? error}`);
|
|
4566
|
-
return null;
|
|
4567
|
-
}
|
|
4568
|
-
}
|
|
4569
|
-
|
|
4570
|
-
/* ------------------------------------------------------------------ */
|
|
4571
|
-
/* Cloudflare agent tool */
|
|
4572
|
-
/* ------------------------------------------------------------------ */
|
|
4573
|
-
|
|
4574
|
-
/** `cloudflare` 工具的参数 schema(只允许宿主支持的 JSON Schema 子集)。 */
|
|
4575
|
-
const CF_TOOL_PARAMETERS = {
|
|
4576
|
-
type: 'object',
|
|
4577
|
-
properties: {
|
|
4578
|
-
action: {
|
|
4579
|
-
type: 'string',
|
|
4580
|
-
enum: ['accounts', 'overview', 'projects', 'workers', 'zones', 'detect', 'deploy', 'review'],
|
|
4581
|
-
description: '要执行的操作:accounts(已登录 Cloudflare 账号)、overview(账户概览)、projects(Pages 项目)、workers(Workers 列表)、zones(域名)、detect(探测目录类型)、deploy(部署 Pages/Worker)、review(部署前审查)。',
|
|
4582
|
-
},
|
|
4583
|
-
path: {
|
|
4584
|
-
type: 'string',
|
|
4585
|
-
description: 'detect/deploy/review 时的目录绝对路径;省略则用当前会话工作目录。',
|
|
4586
|
-
},
|
|
4587
|
-
kind: {
|
|
4588
|
-
type: 'string',
|
|
4589
|
-
enum: ['pages', 'worker'],
|
|
4590
|
-
description: 'deploy/review 时指定部署类型;省略则自动探测。',
|
|
4591
|
-
},
|
|
4592
|
-
project: {
|
|
4593
|
-
type: 'string',
|
|
4594
|
-
description: 'deploy 时 Pages 项目名。',
|
|
4595
|
-
},
|
|
4596
|
-
name: {
|
|
4597
|
-
type: 'string',
|
|
4598
|
-
description: 'deploy 时 Worker 名。',
|
|
4599
|
-
},
|
|
4600
|
-
presetIds: {
|
|
4601
|
-
type: 'array',
|
|
4602
|
-
items: { type: 'string' },
|
|
4603
|
-
description: 'review 时要使用的内置审查项 id。',
|
|
4604
|
-
},
|
|
4605
|
-
customPrompt: {
|
|
4606
|
-
type: 'string',
|
|
4607
|
-
description: 'review 时的额外审查要求。',
|
|
4608
|
-
},
|
|
4609
|
-
},
|
|
4610
|
-
required: ['action'],
|
|
4611
|
-
};
|
|
4612
|
-
|
|
4613
|
-
/** `cloudflare` 工具输出 schema。 */
|
|
4614
|
-
const CF_TOOL_OUTPUT_SCHEMA = {
|
|
4615
|
-
type: 'object',
|
|
4616
|
-
additionalProperties: true,
|
|
4617
|
-
properties: {
|
|
4618
|
-
action: { type: 'string' },
|
|
4619
|
-
},
|
|
4620
|
-
};
|
|
4621
|
-
|
|
4622
|
-
/** 渲染 `cloudflare` 工具结果为模型读的文本。 */
|
|
4623
|
-
function renderCloudflareResult(value) {
|
|
4624
|
-
const action = String(value?.action ?? '');
|
|
4625
|
-
if (action === 'accounts') {
|
|
4626
|
-
const accounts = value.accounts ?? [];
|
|
4627
|
-
if (accounts.length === 0) return '【accounts】还没有登录任何 Cloudflare 账号。';
|
|
4628
|
-
return ['【accounts】']
|
|
4629
|
-
.concat(accounts.map((a) => ` ${a.login}${a.id === value.activeId ? '(当前)' : ''}${a.accountName ? ' · ' + a.accountName : ''}`))
|
|
4630
|
-
.join('\n');
|
|
4631
|
-
}
|
|
4632
|
-
if (action === 'overview') {
|
|
4633
|
-
const pages = value.pages?.count ?? 0;
|
|
4634
|
-
const workers = value.workers?.count ?? 0;
|
|
4635
|
-
const zones = value.zones?.count ?? 0;
|
|
4636
|
-
return `【overview】Pages 项目 ${pages} · Workers ${workers} · 域名 ${zones}`;
|
|
4637
|
-
}
|
|
4638
|
-
if (action === 'projects') {
|
|
4639
|
-
const items = value.items ?? [];
|
|
4640
|
-
if (items.length === 0) return '【projects】没有 Pages 项目。';
|
|
4641
|
-
return ['【projects】'].concat(items.map((p) => ` ${p.name}${p.latestUrl ? ' · ' + p.latestUrl : ''}`)).join('\n');
|
|
4642
|
-
}
|
|
4643
|
-
if (action === 'workers') {
|
|
4644
|
-
const items = value.items ?? [];
|
|
4645
|
-
if (items.length === 0) return '【workers】没有 Workers。';
|
|
4646
|
-
return ['【workers】'].concat(items.map((w) => ` ${w.name}`)).join('\n');
|
|
4647
|
-
}
|
|
4648
|
-
if (action === 'zones') {
|
|
4649
|
-
const items = value.items ?? [];
|
|
4650
|
-
if (items.length === 0) return '【zones】没有域名。';
|
|
4651
|
-
return ['【zones】'].concat(items.map((z) => ` ${z.name}(${z.status})`)).join('\n');
|
|
4652
|
-
}
|
|
4653
|
-
if (action === 'detect') {
|
|
4654
|
-
if (!value.kind) return '【detect】这个目录既不是 Pages 静态产物,也不是 Worker 项目。';
|
|
4655
|
-
return `【detect】检测为 ${value.kind === 'pages' ? 'Pages 静态站点' : 'Worker 项目'}。`;
|
|
4656
|
-
}
|
|
4657
|
-
if (action === 'deploy') {
|
|
4658
|
-
if (value.kind === 'pages') return `【deploy】Pages「${value.project}」部署完成:${value.deployment?.url || ''}`;
|
|
4659
|
-
if (value.kind === 'worker') return `【deploy】Worker「${value.name}」部署完成:${value.url || ''}`;
|
|
4660
|
-
}
|
|
4661
|
-
return JSON.stringify(value);
|
|
4662
|
-
}
|
|
4663
|
-
|
|
4664
|
-
function registerCloudflareTool(ctx, host) {
|
|
4665
|
-
const tools = typeof ctx.get === 'function' ? ctx.get('tools') : ctx.tools;
|
|
4666
|
-
if (!tools || typeof tools.register !== 'function') return null;
|
|
4667
|
-
|
|
4668
|
-
const definition = {
|
|
4669
|
-
name: 'cloudflare',
|
|
4670
|
-
description:
|
|
4671
|
-
'操作当前账号的 Cloudflare 资源:查看已登录账号与账户概览(Pages 项目数 / Workers 数 / 域名数)、列出 Pages 项目、Workers 和域名,'
|
|
4672
|
-
+ '以及探测目录类型、部署 Pages 静态站点或 Worker、部署前审查。'
|
|
4673
|
-
+ '所有输出为中文文本。部署/审查默认作用于当前会话工作目录,需要别的目录时传绝对路径 path。'
|
|
4674
|
-
+ 'API Token 或 Global API Key 由插件里已登录的当前账号提供,绝不写进代码或配置。',
|
|
4675
|
-
parameters: CF_TOOL_PARAMETERS,
|
|
4676
|
-
output: {
|
|
4677
|
-
schema: CF_TOOL_OUTPUT_SCHEMA,
|
|
4678
|
-
render: (_args, value) => [{ type: 'text', text: renderCloudflareResult(value) }],
|
|
4679
|
-
},
|
|
4680
|
-
timeoutMs: 200_000,
|
|
4681
|
-
isConcurrencySafe: () => false,
|
|
4682
|
-
async execute(args, exec) {
|
|
4683
|
-
exec?.signal?.throwIfAborted?.();
|
|
4684
|
-
const sessionCwd = exec?.agent?.session?.header?.cwd
|
|
4685
|
-
?? exec?.agent?.session?.cwd
|
|
4686
|
-
?? undefined;
|
|
4687
|
-
try {
|
|
4688
|
-
return await host.cloudflareToolCall(args ?? {}, {
|
|
4689
|
-
resolvePath: async () => (typeof sessionCwd === 'string' ? sessionCwd : process.cwd()),
|
|
4690
|
-
});
|
|
4691
|
-
} catch (error) {
|
|
4692
|
-
const wire = toWireError(error, (text) => redactSecrets(text));
|
|
4693
|
-
throw new Error(`[${wire.code}] ${wire.message}`);
|
|
4694
|
-
}
|
|
4695
|
-
},
|
|
4696
|
-
};
|
|
4697
|
-
|
|
4698
|
-
try {
|
|
4699
|
-
const dispose = tools.register(definition);
|
|
4700
|
-
return () => {
|
|
4701
|
-
if (typeof dispose === 'function') dispose();
|
|
4702
|
-
};
|
|
4703
|
-
} catch (error) {
|
|
4704
|
-
console?.warn?.(`dsh-push: cloudflare 工具注册失败:${error?.message ?? error}`);
|
|
4705
|
-
return null;
|
|
4706
|
-
}
|
|
4707
|
-
}
|
|
4708
|
-
|
|
4709
|
-
/** Resolve the git binary this host would use right now (diagnostics). */
|
|
4710
|
-
export function currentGitBinary(gitPath) {
|
|
4711
|
-
return resolveGitBinary(gitPath);
|
|
4712
|
-
}
|
|
4713
|
-
|
|
4714
|
-
export { GitError, GithubError };
|
|
4715
|
-
|
|
4716
|
-
export default GithubLinkHost;
|