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