dsh-devdock-github 0.0.0-stage → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2118 @@
1
+ /**
2
+ * DevDock · GitHub / Git 平台插件 · Host 实现。
3
+ *
4
+ * 这个模块不认识内核:它拿到一个经过内核裁剪的 `context`(存储、错误构造、
5
+ * 校验函数),返回一份标准平台定义。内核负责把 routes 挂到 webServer、把
6
+ * actions 聚合进 `devdock` 工具。
7
+ *
8
+ * ## 路由前缀
9
+ *
10
+ * 内核把平台路由挂在 `/api/push/<平台 id>` 之下。所以这里的 `path` 是
11
+ * **平台内相对路径**:`/repos` 实际是 `/api/push/github/repos`。客户端对应
12
+ * `const API = core.API + '/github'`,两边各写一次平台 id,绝不重复。
13
+ *
14
+ * 注意这与全量包的 `/api/push/repos` **不重叠**,所以本插件与全量包可以
15
+ * 同时安装(只是界面会重复,见 README 的「两条安装路线」)。
16
+ *
17
+ * ## 审查不在这里
18
+ *
19
+ * 推送前审查已独立成 `dsh-devdock-review`。本包不提供审查方法,也没有
20
+ * `/review/*` 路由;客户端用 `core.useCapability('review')` 探测它在不在。
21
+ *
22
+ * ## 与内核的分工
23
+ *
24
+ * - GitHub REST:本包 `./github.js`(零第三方依赖)
25
+ * - 本地 Git 命令:内核 `dsh-devdock-core/src/host/git.js` —— npm 与 Cloudflare
26
+ * 的部署也要用它,所以是共享件,不复制
27
+ * - 账号与设置存储:`context.store`
28
+ *
29
+ * @module src/host/platform.js
30
+ */
31
+
32
+ import { readFile, writeFile, stat } from 'node:fs/promises';
33
+ import path from 'node:path';
34
+
35
+ import {
36
+ GitRunner,
37
+ githubPushUrl,
38
+ isGithubUrl,
39
+ parseGithubRemote,
40
+ } from 'dsh-devdock-core/src/host/git.js';
41
+ import { redactSecrets } from 'dsh-devdock-core/src/host/store.js';
42
+
43
+ import {
44
+ addCollaborator,
45
+ contributions as fetchContributions,
46
+ createRelease,
47
+ createRepo,
48
+ deleteBranchRemote,
49
+ deleteRelease,
50
+ deleteReleaseAsset,
51
+ listNotifications,
52
+ listReleases,
53
+ listRepos,
54
+ markNotificationRead,
55
+ pollDeviceFlow,
56
+ protectBranch,
57
+ removeCollaborator,
58
+ renameBranch,
59
+ renameRepo,
60
+ repoDetail as fetchRepoDetail,
61
+ repoLanguages as fetchRepoLanguages,
62
+ repoManage as fetchRepoManage,
63
+ searchRepos,
64
+ startDeviceFlow,
65
+ transferRepo,
66
+ updateRelease,
67
+ updateRepo,
68
+ uploadReleaseAsset,
69
+ verifyToken,
70
+ } from './github.js';
71
+
72
+ /**
73
+ * 空的本机状态文档(`isRepo: false`),形状与 CONTRACT §3 一致。
74
+ *
75
+ * 客户端用它渲染「未初始化」面板,所以**必须**是同一形状,否则那条分支要
76
+ * 再写一套渲染代码。原本是元包的模块级函数,切片时最容易漏——第一次就漏了,
77
+ * 表现为打开没有 git 的目录时 ReferenceError。
78
+ *
79
+ * @returns {object}
80
+ */
81
+ function emptyStatus() {
82
+ return {
83
+ isRepo: false,
84
+ root: null,
85
+ gitDir: null,
86
+ branch: null,
87
+ detachedHead: false,
88
+ upstream: null,
89
+ ahead: 0,
90
+ behind: 0,
91
+ remotes: [],
92
+ githubRemote: null,
93
+ head: null,
94
+ dirty: { changed: 0, staged: 0, untracked: 0, conflicted: 0 },
95
+ files: [],
96
+ tags: [],
97
+ branches: [],
98
+ stashes: [],
99
+ };
100
+ }
101
+
102
+ /**
103
+ * 平台定义工厂。
104
+ *
105
+ * @param {object} context 内核注入的平台上下文
106
+ * @returns {object} 归一化前的平台定义
107
+ */
108
+ export function githubPlatform(context) {
109
+ const {
110
+ store,
111
+ httpError,
112
+ requireString,
113
+ optionalString,
114
+ optionalBool,
115
+ } = context;
116
+
117
+ /* git --version 的短缓存:设置页会轮询 /state,每次都 spawn 太浪费。
118
+ * 10 秒足够快,也足够让"刚装了 git"立刻可见。 */
119
+ let gitProbeCache = null;
120
+ let gitProbeAt = 0;
121
+
122
+ /**
123
+ * `{available, version}` for the git binary,短缓存。
124
+ *
125
+ * 这个方法原本是类成员,靠 `this.#gitProbe` 两个私有字段缓存;迁到这里
126
+ * 改用闭包变量。逻辑不变:同一个 gitPath 在 10 秒内只探测一次。
127
+ *
128
+ * @returns {Promise<{available: boolean, version: string|null}>}
129
+ */
130
+ async function probeGit() {
131
+ const settings = await store.settings();
132
+ const key = settings.gitPath;
133
+ const now = Date.now();
134
+ if (gitProbeCache && gitProbeCache.key === key && now - gitProbeAt < 10_000) {
135
+ return gitProbeCache.value;
136
+ }
137
+ const gitRunner = new GitRunner({ gitPath: key });
138
+ let value;
139
+ try {
140
+ value = await gitRunner.probe();
141
+ } catch {
142
+ value = { available: false, version: null };
143
+ }
144
+ gitProbeCache = { key, value };
145
+ gitProbeAt = now;
146
+ return value;
147
+ }
148
+
149
+ /**
150
+ * A runner bound to the CURRENT `gitPath` setting.
151
+ *
152
+ * Constructing one per call is deliberate: it costs nothing, and it means a
153
+ * settings change applies to the next command instead of after a restart.
154
+ * @returns {Promise<GitRunner>}
155
+ */
156
+ async function runner() {
157
+ const settings = await store.settings();
158
+ return new GitRunner({ gitPath: settings.gitPath });
159
+ }
160
+
161
+ /** Every token we hold, for output redaction. */
162
+ async function ownSecrets() {
163
+ return store.secrets();
164
+ }
165
+
166
+ /** Redact known tokens from arbitrary text. */
167
+ async function scrub(text) {
168
+ return redactSecrets(text, await ownSecrets());
169
+ }
170
+
171
+ /**
172
+ * The active account WITH its token, or NO_ACCOUNT.
173
+ * @returns {Promise<object>}
174
+ */
175
+ async function requireAccount() {
176
+ const account = await store.activeAccount();
177
+ if (!account) {
178
+ throw httpError(400, 'NO_ACCOUNT', '还没有登录 GitHub 账号,请先在设置里添加账号。');
179
+ }
180
+ return account;
181
+ }
182
+
183
+ /**
184
+ * Refresh `lastUsedAt` for an account after it was actually used against
185
+ * GitHub. Failures are swallowed: a bookkeeping write must never fail a
186
+ * successful API call.
187
+ * @param {string} accountId
188
+ */
189
+ async function touch(accountId) {
190
+ try {
191
+ await store.mutate((state) => {
192
+ const account = state.accounts.find((row) => row.id === accountId);
193
+ if (account) account.lastUsedAt = new Date().toISOString();
194
+ });
195
+ } catch {
196
+ // best effort
197
+ }
198
+ }
199
+
200
+ /**
201
+ * `POST /accounts/token` — validate then upsert (same login replaces).
202
+ * @param {{token: string}} body
203
+ * @returns {Promise<{accounts: object[], activeAccountId: string|null}>}
204
+ */
205
+ async function addTokenAccount(body) {
206
+ const token = requireString(body, 'token', ' GitHub 令牌');
207
+ const profile = await verifyToken(token);
208
+ const id = profile.login.toLowerCase();
209
+ const result = await store.mutate((state) => {
210
+ const now = new Date().toISOString();
211
+ const existing = state.accounts.find((account) => account.id === id);
212
+ const record = {
213
+ id,
214
+ login: profile.login,
215
+ name: profile.name,
216
+ avatarUrl: profile.avatarUrl,
217
+ htmlUrl: profile.htmlUrl,
218
+ token,
219
+ tokenKind: 'pat',
220
+ scopes: profile.scopes,
221
+ addedAt: existing?.addedAt ?? now,
222
+ lastUsedAt: now,
223
+ };
224
+ if (existing) state.accounts = state.accounts.map((account) => (account.id === id ? record : account));
225
+ else state.accounts = [...state.accounts, record];
226
+ // Signing in a NEW account makes it active; re-submitting an existing
227
+ // token must not steal the selection from the account the user is using.
228
+ if (!existing || state.activeAccountId === null) state.activeAccountId = id;
229
+ return { accounts: state.accounts.map(publicAccount), activeAccountId: state.activeAccountId };
230
+ });
231
+ return result;
232
+ }
233
+
234
+ /**
235
+ * `POST /accounts/device/start` — begin the OAuth device flow.
236
+ * @returns {Promise<object>}
237
+ */
238
+ async function deviceStart() {
239
+ const settings = await store.settings();
240
+ return startDeviceFlow({ clientId: settings.oauthClientId });
241
+ }
242
+
243
+ /**
244
+ * `POST /accounts/device/poll` — one poll; stores the account on success.
245
+ * @param {{deviceCode: string}} body
246
+ * @returns {Promise<object>}
247
+ */
248
+ async function devicePoll(body) {
249
+ const deviceCode = requireString(body, 'deviceCode', ' deviceCode');
250
+ const settings = await store.settings();
251
+ const polled = await pollDeviceFlow({ clientId: settings.oauthClientId, deviceCode });
252
+ if (polled.status !== 'done' || typeof polled.token !== 'string') return { status: polled.status };
253
+
254
+ // The OAuth token is validated through the same /user call as a PAT, so an
255
+ // account record has identical fields regardless of how it was obtained.
256
+ const profile = await verifyToken(polled.token);
257
+ const id = profile.login.toLowerCase();
258
+ const stored = await store.mutate((state) => {
259
+ const now = new Date().toISOString();
260
+ const existing = state.accounts.find((account) => account.id === id);
261
+ const record = {
262
+ id,
263
+ login: profile.login,
264
+ name: profile.name,
265
+ avatarUrl: profile.avatarUrl,
266
+ htmlUrl: profile.htmlUrl,
267
+ token: polled.token,
268
+ tokenKind: 'oauth',
269
+ scopes: profile.scopes,
270
+ addedAt: existing?.addedAt ?? now,
271
+ lastUsedAt: now,
272
+ };
273
+ if (existing) state.accounts = state.accounts.map((account) => (account.id === id ? record : account));
274
+ else state.accounts = [...state.accounts, record];
275
+ state.activeAccountId = id;
276
+ return { accounts: state.accounts.map(publicAccount), activeAccountId: state.activeAccountId };
277
+ });
278
+ return { status: 'done', ...stored };
279
+ }
280
+
281
+ /**
282
+ * `POST /accounts/activate`.
283
+ * @param {{accountId: string}} body
284
+ * @returns {Promise<{activeAccountId: string}>}
285
+ */
286
+ async function activateAccount(body) {
287
+ const accountId = requireString(body, 'accountId', ' accountId');
288
+ const activeAccountId = await store.mutate((state) => {
289
+ const found = state.accounts.find((account) => account.id === accountId);
290
+ if (!found) throw httpError(404, 'NOT_FOUND', `找不到账号 ${accountId}`);
291
+ state.activeAccountId = accountId;
292
+ return accountId;
293
+ });
294
+ return { activeAccountId };
295
+ }
296
+
297
+ /**
298
+ * `POST /accounts/remove`.
299
+ * @param {{accountId: string}} body
300
+ * @returns {Promise<{accounts: object[], activeAccountId: string|null}>}
301
+ */
302
+ async function removeAccount(body) {
303
+ const accountId = requireString(body, 'accountId', ' accountId');
304
+ return store.mutate((state) => {
305
+ if (!state.accounts.some((account) => account.id === accountId)) {
306
+ throw httpError(404, 'NOT_FOUND', `找不到账号 ${accountId}`);
307
+ }
308
+ state.accounts = state.accounts.filter((account) => account.id !== accountId);
309
+ if (state.activeAccountId === accountId) {
310
+ // Fall back to the first remaining account so the panel is never left
311
+ // showing "active: <deleted>" — or no active account while one exists.
312
+ state.activeAccountId = state.accounts[0]?.id ?? null;
313
+ }
314
+ return { accounts: state.accounts.map(publicAccount), activeAccountId: state.activeAccountId };
315
+ });
316
+ }
317
+
318
+ /**
319
+ * `GET /repos` — list or search.
320
+ * @param {{page?: string|number, q?: string, affiliation?: string, sort?: string}} query
321
+ * @returns {Promise<object>}
322
+ */
323
+ async function repos(query) {
324
+ const account = await requireAccount();
325
+ const page = clampInt(query.page, 1, 1000, 1);
326
+ const q = optionalString(query.q);
327
+ const result = q
328
+ ? await searchRepos({ token: account.token, login: account.login, q, page })
329
+ : await listRepos({
330
+ token: account.token,
331
+ page,
332
+ affiliation: optionalString(query.affiliation),
333
+ sort: optionalString(query.sort),
334
+ });
335
+ await touch(account.id);
336
+ return result;
337
+ }
338
+
339
+ /**
340
+ * `GET /repos/detail`.
341
+ * @param {{owner: string, name: string}} query
342
+ * @returns {Promise<object>}
343
+ */
344
+ async function repoDetail(query) {
345
+ const account = await requireAccount();
346
+ const owner = requireString(query, 'owner', ' owner');
347
+ const name = requireString(query, 'name', ' name');
348
+ const result = await fetchRepoDetail({ token: account.token, owner, name });
349
+ await touch(account.id);
350
+ return result;
351
+ }
352
+
353
+ /**
354
+ * `POST /repos/create`.
355
+ * @param {object} body
356
+ * @returns {Promise<object>}
357
+ */
358
+ async function repoCreate(body) {
359
+ const account = await requireAccount();
360
+ const name = requireString(body, 'name', '仓库名称');
361
+ const result = await createRepo({
362
+ token: account.token,
363
+ name,
364
+ owner: optionalString(body.owner),
365
+ login: account.login,
366
+ private: optionalBool(body.private, true),
367
+ description: optionalString(body.description) ?? '',
368
+ autoInit: optionalBool(body.autoInit, false),
369
+ });
370
+ await touch(account.id);
371
+ return result;
372
+ }
373
+
374
+ /**
375
+ * `POST /repos/delete`.
376
+ * @param {object} body
377
+ * @returns {Promise<{deleted: true}>}
378
+ */
379
+ async function repoDelete(body) {
380
+ const account = await requireAccount();
381
+ const owner = requireString(body, 'owner', ' owner');
382
+ const name = requireString(body, 'name', '仓库名称');
383
+ // Deleting a repository is irreversible and needs the delete_repo
384
+ // scope, so it is gated exactly like rename/transfer: a bare call with no
385
+ // explicit confirmation is a mistake, not an intent.
386
+ if (optionalBool(body.confirm, false) !== true) {
387
+ throw httpError(
388
+ 409,
389
+ 'CONFLICT',
390
+ `删除仓库会永久移除 ${owner}/${name} 在 GitHub 上的全部代码、Issue、PR 与发布,无法撤销,且需要令牌具备 delete_repo 权限范围。请确认后再执行(confirm: true)。`,
391
+ );
392
+ }
393
+ const result = await deleteRepo({ token: account.token, owner, name });
394
+ await touch(account.id);
395
+ return result;
396
+ }
397
+
398
+ /**
399
+ * `GET /repos/manage` — the management dialog's aggregate (CONTRACT §3c).
400
+ *
401
+ * Partial failure is the NORMAL case here: a token with `repo` but without
402
+ * `admin:repo_hook` still gets stars, branches and releases, and only the
403
+ * webhook field comes back `null` with a Chinese warning. `github.js` does
404
+ * the `Promise.allSettled` fan-out; this method only supplies the account.
405
+ *
406
+ * @param {{owner: string, name: string}} query
407
+ * @returns {Promise<object>}
408
+ */
409
+ async function repoManage(query) {
410
+ const account = await requireAccount();
411
+ const owner = requireString(query, 'owner', ' owner');
412
+ const name = requireString(query, 'name', ' name');
413
+ const result = await fetchRepoManage({ token: account.token, owner, name });
414
+ await touch(account.id);
415
+ return result;
416
+ }
417
+
418
+ /**
419
+ * `POST /repos/update` — edit repository metadata (CONTRACT §3c).
420
+ * @param {object} body
421
+ * @returns {Promise<object>}
422
+ */
423
+ async function repoUpdate(body) {
424
+ const account = await requireAccount();
425
+ const owner = requireString(body, 'owner', ' owner');
426
+ const name = requireString(body, 'name', ' name');
427
+ const patch = {};
428
+ // Every field is optional; only the ones present are forwarded, so the
429
+ // route can no longer wipe a description the user did not edit.
430
+ if (body.description !== undefined) {
431
+ if (typeof body.description !== 'string') throw httpError(400, 'BAD_REQUEST', 'description 必须是字符串');
432
+ patch.description = body.description;
433
+ }
434
+ if (body.homepage !== undefined) {
435
+ if (typeof body.homepage !== 'string') throw httpError(400, 'BAD_REQUEST', 'homepage 必须是字符串');
436
+ patch.homepage = body.homepage;
437
+ }
438
+ if (body.private !== undefined) {
439
+ if (typeof body.private !== 'boolean') throw httpError(400, 'BAD_REQUEST', 'private 必须是布尔值');
440
+ patch.private = body.private;
441
+ }
442
+ if (body.archived !== undefined) {
443
+ if (typeof body.archived !== 'boolean') throw httpError(400, 'BAD_REQUEST', 'archived 必须是布尔值');
444
+ patch.archived = body.archived;
445
+ }
446
+ if (body.topics !== undefined) {
447
+ if (!Array.isArray(body.topics)) throw httpError(400, 'BAD_REQUEST', 'topics 必须是字符串数组');
448
+ patch.topics = body.topics.filter((topic) => typeof topic === 'string');
449
+ }
450
+ if (body.defaultBranch !== undefined) {
451
+ if (typeof body.defaultBranch !== 'string') throw httpError(400, 'BAD_REQUEST', 'defaultBranch 必须是字符串');
452
+ patch.defaultBranch = body.defaultBranch;
453
+ }
454
+ const result = await updateRepo({ token: account.token, owner, name, patch });
455
+ await touch(account.id);
456
+ // A topics-only change issues no PATCH, so there is no repository payload;
457
+ // refetch it so every caller keeps receiving a complete repo object.
458
+ if (!result.repo) {
459
+ const refreshed = await fetchRepoDetail({ token: account.token, owner, name });
460
+ return { repo: refreshed.repo, topics: result.topics };
461
+ }
462
+ return result;
463
+ }
464
+
465
+ /**
466
+ * `POST /repos/branch/rename`.
467
+ * @param {object} body
468
+ * @returns {Promise<object>}
469
+ */
470
+ async function repoBranchRename(body) {
471
+ const account = await requireAccount();
472
+ const owner = requireString(body, 'owner', ' owner');
473
+ const name = requireString(body, 'name', ' name');
474
+ const from = requireString(body, 'from', '原分支名');
475
+ const to = requireString(body, 'to', '新分支名');
476
+ const result = await renameBranch({ token: account.token, owner, name, from, to });
477
+ await touch(account.id);
478
+ return result;
479
+ }
480
+
481
+ /**
482
+ * `POST /repos/branch/delete`.
483
+ * @param {object} body
484
+ * @returns {Promise<object>}
485
+ */
486
+ async function repoBranchDelete(body) {
487
+ const account = await requireAccount();
488
+ const owner = requireString(body, 'owner', ' owner');
489
+ const name = requireString(body, 'name', ' name');
490
+ const branch = requireString(body, 'branch', '分支名');
491
+ const result = await deleteBranchRemote({ token: account.token, owner, name, branch });
492
+ await touch(account.id);
493
+ return result;
494
+ }
495
+
496
+ /**
497
+ * `POST /repos/branch/protect`.
498
+ * @param {object} body
499
+ * @returns {Promise<object>}
500
+ */
501
+ async function repoBranchProtect(body) {
502
+ const account = await requireAccount();
503
+ const owner = requireString(body, 'owner', ' owner');
504
+ const name = requireString(body, 'name', ' name');
505
+ const branch = requireString(body, 'branch', '分支名');
506
+ if (typeof body.protected !== 'boolean') {
507
+ throw httpError(400, 'BAD_REQUEST', 'protected 必须是布尔值');
508
+ }
509
+ const result = await protectBranch({
510
+ token: account.token,
511
+ owner,
512
+ name,
513
+ branch,
514
+ protected: body.protected,
515
+ });
516
+ await touch(account.id);
517
+ return result;
518
+ }
519
+
520
+ /**
521
+ * `POST /repos/release/delete`.
522
+ * @param {object} body
523
+ * @returns {Promise<object>}
524
+ */
525
+ async function repoReleaseDelete(body) {
526
+ const account = await requireAccount();
527
+ const owner = requireString(body, 'owner', ' owner');
528
+ const name = requireString(body, 'name', ' name');
529
+ const id = requireString(body, 'id', ' release id');
530
+ const result = await deleteRelease({ token: account.token, owner, name, id });
531
+ await touch(account.id);
532
+ return result;
533
+ }
534
+
535
+ /**
536
+ * `POST /repos/release/update`.
537
+ * @param {object} body
538
+ * @returns {Promise<object>}
539
+ */
540
+ async function repoReleaseUpdate(body) {
541
+ const account = await requireAccount();
542
+ const owner = requireString(body, 'owner', ' owner');
543
+ const name = requireString(body, 'name', ' name');
544
+ const id = requireString(body, 'id', ' release id');
545
+ const patch = {};
546
+ // `body.name` is the REPOSITORY name (used above), so the release title
547
+ // must arrive under its own key. Accepting `name` here made it
548
+ // impossible to set a title without corrupting the repository path.
549
+ const releaseName = optionalString(body.releaseName) ?? optionalString(body.title);
550
+ if (releaseName !== undefined) {
551
+ patch.name = releaseName;
552
+ }
553
+ if (body.body !== undefined) {
554
+ if (typeof body.body !== 'string') throw httpError(400, 'BAD_REQUEST', 'body 必须是字符串');
555
+ patch.body = body.body;
556
+ }
557
+ if (body.draft !== undefined) {
558
+ if (typeof body.draft !== 'boolean') throw httpError(400, 'BAD_REQUEST', 'draft 必须是布尔值');
559
+ patch.draft = body.draft;
560
+ }
561
+ if (body.prerelease !== undefined) {
562
+ if (typeof body.prerelease !== 'boolean') throw httpError(400, 'BAD_REQUEST', 'prerelease 必须是布尔值');
563
+ patch.prerelease = body.prerelease;
564
+ }
565
+ // Never spread `patch` into an object that already has `name`: the spread
566
+ // overwrote the repository name with the release title.
567
+ const result = await updateRelease({
568
+ token: account.token,
569
+ owner,
570
+ repo: name,
571
+ id,
572
+ title: patch.name,
573
+ body: patch.body,
574
+ draft: patch.draft,
575
+ prerelease: patch.prerelease,
576
+ });
577
+ await touch(account.id);
578
+ return result;
579
+ }
580
+
581
+ /**
582
+ * `POST /repos/collaborator/add`.
583
+ * @param {object} body
584
+ * @returns {Promise<object>}
585
+ */
586
+ async function repoCollaboratorAdd(body) {
587
+ const account = await requireAccount();
588
+ const owner = requireString(body, 'owner', ' owner');
589
+ const name = requireString(body, 'name', ' name');
590
+ const user = requireString(body, 'user', ' GitHub 用户名');
591
+ const permission = optionalString(body.permission) ?? 'push';
592
+ const result = await addCollaborator({ token: account.token, owner, name, user, permission });
593
+ await touch(account.id);
594
+ return result;
595
+ }
596
+
597
+ /**
598
+ * `POST /repos/collaborator/remove`.
599
+ * @param {object} body
600
+ * @returns {Promise<object>}
601
+ */
602
+ async function repoCollaboratorRemove(body) {
603
+ const account = await requireAccount();
604
+ const owner = requireString(body, 'owner', ' owner');
605
+ const name = requireString(body, 'name', ' name');
606
+ const user = requireString(body, 'user', ' GitHub 用户名');
607
+ const result = await removeCollaborator({ token: account.token, owner, name, user });
608
+ await touch(account.id);
609
+ return result;
610
+ }
611
+
612
+ /**
613
+ * `POST /repos/rename` — destructive; requires `confirm: true`.
614
+ *
615
+ * The confirmation pattern (and its wording) is copied from `/local/reset`
616
+ * and `/local/discard-all`: a 409 CONFLICT that says exactly what will
617
+ * happen and what field acknowledges it.
618
+ *
619
+ * @param {object} body
620
+ * @returns {Promise<object>}
621
+ */
622
+ async function repoRename(body) {
623
+ const account = await requireAccount();
624
+ const owner = requireString(body, 'owner', ' owner');
625
+ const name = requireString(body, 'name', ' name');
626
+ const newName = requireString(body, 'newName', '新仓库名称');
627
+ if (optionalBool(body.confirm, false) !== true) {
628
+ throw httpError(
629
+ 409,
630
+ 'CONFLICT',
631
+ `重命名仓库会改变它的地址:旧链接会被 GitHub 重定向,但本地远端、其他协作者的克隆都需要手动更新。请确认后再执行(confirm: true)。`,
632
+ );
633
+ }
634
+ const result = await renameRepo({ token: account.token, owner, name, newName });
635
+ await touch(account.id);
636
+ return result;
637
+ }
638
+
639
+ /**
640
+ * `POST /repos/transfer` — destructive; requires `confirm: true`.
641
+ * @param {object} body
642
+ * @returns {Promise<object>}
643
+ */
644
+ async function repoTransfer(body) {
645
+ const account = await requireAccount();
646
+ const owner = requireString(body, 'owner', ' owner');
647
+ const name = requireString(body, 'name', ' name');
648
+ const newOwner = requireString(body, 'newOwner', '新的仓库所有者');
649
+ if (optionalBool(body.confirm, false) !== true) {
650
+ throw httpError(
651
+ 409,
652
+ 'CONFLICT',
653
+ `转移仓库会把它移交给 ${newOwner},原所有者将失去管理权限,且 Webhook、协作者与 Actions 配置可能失效。请确认后再执行(confirm: true)。`,
654
+ );
655
+ }
656
+ const result = await transferRepo({ token: account.token, owner, name, newOwner });
657
+ await touch(account.id);
658
+ return result;
659
+ }
660
+
661
+ /**
662
+ * `GET /releases`.
663
+ * @param {{owner: string, repo: string}} query
664
+ * @returns {Promise<object>}
665
+ */
666
+ async function releases(query) {
667
+ const account = await requireAccount();
668
+ const owner = requireString(query, 'owner', ' owner');
669
+ const repo = requireString(query, 'repo', '仓库名称');
670
+ const result = await listReleases({ token: account.token, owner, repo });
671
+ await touch(account.id);
672
+ return result;
673
+ }
674
+
675
+ /**
676
+ * `POST /releases`.
677
+ * @param {object} body
678
+ * @returns {Promise<object>}
679
+ */
680
+ async function releaseCreate(body) {
681
+ const account = await requireAccount();
682
+ const owner = requireString(body, 'owner', ' owner');
683
+ const repo = requireString(body, 'repo', '仓库名称');
684
+ const tagName = requireString(body, 'tagName', '标签名');
685
+ const result = await createRelease({
686
+ token: account.token,
687
+ owner,
688
+ repo,
689
+ tagName,
690
+ name: optionalString(body.name),
691
+ body: optionalString(body.body),
692
+ target: optionalString(body.target),
693
+ draft: optionalBool(body.draft, false),
694
+ prerelease: optionalBool(body.prerelease, false),
695
+ });
696
+ await touch(account.id);
697
+ return result;
698
+ }
699
+
700
+ /**
701
+ * `GET /contributions` — the active account's contribution calendar.
702
+ *
703
+ * `login` defaults to the ACTIVE account so the panel can ask with no
704
+ * arguments; naming another user is allowed because GitHub's calendar is
705
+ * public for public activity. A token without `read:user` resolves to
706
+ * `{unavailable:true}` rather than an error, so the page keeps rendering.
707
+ *
708
+ * @param {{login?: string, days?: string|number}} query
709
+ * @returns {Promise<object>}
710
+ */
711
+ async function contributions(query) {
712
+ const account = await requireAccount();
713
+ const login = optionalString(query.login) ?? account.login;
714
+ const result = await fetchContributions({
715
+ token: account.token,
716
+ login,
717
+ days: clampInt(query.days, 1, 365, 365),
718
+ });
719
+ // A scope-denied answer never reached GitHub's data, so it is not "use".
720
+ if (result.unavailable !== true) await touch(account.id);
721
+ return result;
722
+ }
723
+
724
+ /**
725
+ * `GET /notifications` — recent notification threads ("最近消息").
726
+ * @param {{all?: string, limit?: string|number}} query
727
+ * @returns {Promise<{items: object[], unreadCount: number}>}
728
+ */
729
+ async function notifications(query) {
730
+ const account = await requireAccount();
731
+ const result = await listNotifications({
732
+ token: account.token,
733
+ // Query strings carry text, so `true`/`1` are the accepted truthy forms;
734
+ // anything else means "unread only", which is GitHub's own default.
735
+ all: query.all === 'true' || query.all === '1',
736
+ limit: clampInt(query.limit, 1, 50, 30),
737
+ });
738
+ await touch(account.id);
739
+ return result;
740
+ }
741
+
742
+ /**
743
+ * `POST /notifications/read` — mark one thread read.
744
+ * @param {{id: string}} body
745
+ * @returns {Promise<{read: true}>}
746
+ */
747
+ async function notificationRead(body) {
748
+ const account = await requireAccount();
749
+ const id = requireString(body, 'id', '通知 id');
750
+ const result = await markNotificationRead({ token: account.token, id });
751
+ await touch(account.id);
752
+ return result;
753
+ }
754
+
755
+ /**
756
+ * `GET /local/status`.
757
+ *
758
+ * A directory that is not a repository is a NORMAL answer here
759
+ * (`isRepo:false`), not an error: the sidebar's Git tab is opened on arbitrary
760
+ * workspaces, most of which are not repositories.
761
+ * @param {string} path
762
+ * @returns {Promise<object>}
763
+ */
764
+ async function localStatus(path) {
765
+ const target = requireString({ path }, 'path', '仓库路径');
766
+ const settings = await store.settings();
767
+ const runner = new GitRunner({ gitPath: settings.gitPath });
768
+ const secrets = await ownSecrets();
769
+ const probe = await runner.probe();
770
+ if (!probe.available) {
771
+ throw new GitError(
772
+ 'GIT_MISSING',
773
+ `找不到可用的 git(当前使用 ${runner.binary})。请安装 Git,或在插件设置里填写「git 路径」。`,
774
+ );
775
+ }
776
+ try {
777
+ return await runner.status(target, { defaultRemote: settings.defaultRemote, secrets });
778
+ } catch (error) {
779
+ // ONLY "not a repository" degrades to the empty document. A bad argument
780
+ // (a relative path, say) must still be reported: silently answering
781
+ // "not a repo" would hide the real problem from the panel.
782
+ if (error?.code === 'NOT_A_REPO') return emptyStatus();
783
+ throw error;
784
+ }
785
+ }
786
+
787
+ /**
788
+ * `GET /local/log`.
789
+ * @param {{path: string, limit?: string|number, ref?: string}} query
790
+ * @returns {Promise<object>}
791
+ */
792
+ async function localLog(query) {
793
+ const path = requireString(query, 'path', '仓库路径');
794
+ const settings = await store.settings();
795
+ const runner = new GitRunner({ gitPath: settings.gitPath });
796
+ return runner.log(path, {
797
+ limit: clampInt(query.limit, 1, 500, 60),
798
+ ref: optionalString(query.ref),
799
+ secrets: await ownSecrets(),
800
+ });
801
+ }
802
+
803
+ /**
804
+ * `GET /local/diff`.
805
+ * @param {{path: string, file: string, staged?: string}} query
806
+ * @returns {Promise<object>}
807
+ */
808
+ async function localDiff(query) {
809
+ const path = requireString(query, 'path', '仓库路径');
810
+ const file = requireString(query, 'file', '文件路径');
811
+ const settings = await store.settings();
812
+ const runner = new GitRunner({ gitPath: settings.gitPath });
813
+ return runner.diff(path, {
814
+ file,
815
+ staged: query.staged === 'true' || query.staged === '1',
816
+ secrets: await ownSecrets(),
817
+ });
818
+ }
819
+
820
+ /**
821
+ * `GET /local/commit`.
822
+ * @param {{path: string, sha: string}} query
823
+ * @returns {Promise<object>}
824
+ */
825
+ async function localCommitDetail(query) {
826
+ const path = requireString(query, 'path', '仓库路径');
827
+ const sha = requireString(query, 'sha', '提交 SHA');
828
+ const settings = await store.settings();
829
+ const runner = new GitRunner({ gitPath: settings.gitPath });
830
+ return runner.commitDetail(path, { sha, secrets: await ownSecrets() });
831
+ }
832
+
833
+ /**
834
+ * `GET /local/remotes`.
835
+ * @param {{path: string}} query
836
+ * @returns {Promise<object>}
837
+ */
838
+ async function localRemotes(query) {
839
+ const path = requireString(query, 'path', '仓库路径');
840
+ const settings = await store.settings();
841
+ const runner = new GitRunner({ gitPath: settings.gitPath });
842
+ return runner.remotes(path, { secrets: await ownSecrets() });
843
+ }
844
+
845
+ /**
846
+ * The token to attach to one network command, if any.
847
+ *
848
+ * A GitHub **https** remote is authenticated with the active account's token;
849
+ * an ssh remote must NOT get one (git+ssh has its own auth and an injected
850
+ * header would be meaningless). A missing account on an https GitHub remote
851
+ * is reported as NO_ACCOUNT rather than letting git fail with a credential
852
+ * prompt that cannot appear.
853
+ *
854
+ * @param {GitRunner} runner
855
+ * @param {string} path
856
+ * @param {string} remote
857
+ * @returns {Promise<string|undefined>}
858
+ */
859
+ async function tokenForRemote(runner, path, remote) {
860
+ let remotes;
861
+ try {
862
+ remotes = (await runner.remotes(path)).remotes;
863
+ } catch {
864
+ // A repository whose remotes cannot be read gets no token; git's own
865
+ // error is clearer than anything invented here.
866
+ return undefined;
867
+ }
868
+ const target = remotes.find((row) => row.name === remote);
869
+ if (!target || !isGithubUrl(target.url)) return undefined;
870
+ if (!/^https?:/i.test(target.url)) return undefined;
871
+ // The remote's URL is quoted (it is not a secret) because it is what tells
872
+ // the user WHICH remote needs an account.
873
+ return githubHttpsToken(`远端 ${remote}`, `(${target.url})`);
874
+ }
875
+
876
+ /**
877
+ * The active account's token, requiring an account to exist.
878
+ *
879
+ * Shared by the remote-name path and the by-URL path (CONTRACT §3b): an
880
+ * anonymous https push to GitHub is pointless — it can only fail with a
881
+ * credential prompt that this Host deliberately never shows — so both paths
882
+ * fail early with an actionable NO_ACCOUNT.
883
+ *
884
+ * @param {string} what names the destination in the Chinese message.
885
+ * @param {string} [detail] an extra parenthetical (the URL, already scrubbed
886
+ * by the caller — real tokens never reach this argument).
887
+ * @returns {Promise<string>}
888
+ */
889
+ async function githubHttpsToken(what, detail = '') {
890
+ const account = await store.activeAccount();
891
+ if (!account) {
892
+ throw httpError(
893
+ 400,
894
+ 'NO_ACCOUNT',
895
+ `${what} 指向 GitHub${detail},需要先在设置里登录一个 GitHub 账号才能认证。`,
896
+ );
897
+ }
898
+ return account.token;
899
+ }
900
+
901
+ /** Build a runner from the live settings (shared by every local route). */
902
+ async function runnerAndSecrets() {
903
+ const settings = await store.settings();
904
+ return {
905
+ settings,
906
+ runner: new GitRunner({ gitPath: settings.gitPath }),
907
+ secrets: await ownSecrets(),
908
+ };
909
+ }
910
+
911
+ /**
912
+ * The remote a network route should use.
913
+ *
914
+ * The body's `remote` wins; otherwise `settings.defaultRemote` — which exists
915
+ * precisely so a user whose repositories all use `upstream` does not have to
916
+ * name it on every click — and `origin` only as the last resort.
917
+ *
918
+ * @param {string|undefined} requested the body's `remote`.
919
+ * @param {string} defaultRemote the settings value.
920
+ * @returns {string}
921
+ */
922
+ function pickRemote(requested, defaultRemote) {
923
+ const explicit = optionalString(requested);
924
+ if (explicit !== undefined) return explicit;
925
+ const fallback = optionalString(defaultRemote);
926
+ return fallback ?? 'origin';
927
+ }
928
+
929
+ /**
930
+ * `POST /local/init`.
931
+ * @param {object} body
932
+ * @returns {Promise<{output: string}>}
933
+ */
934
+ async function localInit(body) {
935
+ const path = requireString(body, 'path', '仓库路径');
936
+ const { runner, secrets } = await runnerAndSecrets();
937
+ const initOut = await runner.init(path, { secrets });
938
+ let output = initOut.output;
939
+ if (optionalBool(body.createRemote, false)) {
940
+ const account = await requireAccount();
941
+ // The name defaults to the directory's own name, which is what a
942
+ // "create the GitHub repo for this folder" button means.
943
+ const name = optionalString(body.name)
944
+ ?? initOut.root.replace(/[\\/]+$/, '').split(/[\\/]/).pop()
945
+ ?? '';
946
+ if (name === '') throw httpError(400, 'BAD_REQUEST', '缺少仓库名称');
947
+ const created = await createRepo({
948
+ token: account.token,
949
+ name,
950
+ owner: optionalString(body.owner),
951
+ login: account.login,
952
+ private: optionalBool(body.private, true),
953
+ description: '',
954
+ autoInit: false,
955
+ });
956
+ await touch(account.id);
957
+ const remoteName = optionalString(body.remoteName) ?? 'origin';
958
+ const remoteOut = await runner.setRemote(initOut.root, {
959
+ name: remoteName,
960
+ url: created.repo.cloneUrl,
961
+ secrets,
962
+ });
963
+ output += remoteOut.output;
964
+ }
965
+ // Stage everything but do NOT commit: the first commit message is the
966
+ // user's decision, and the contract says so explicitly.
967
+ const staged = await runner.stageAll(initOut.root, { secrets });
968
+ return { output: output + staged.output };
969
+ }
970
+
971
+ /**
972
+ * `POST /local/remote`.
973
+ * @param {object} body
974
+ * @returns {Promise<{output: string}>}
975
+ */
976
+ async function localSetRemote(body) {
977
+ const path = requireString(body, 'path', '仓库路径');
978
+ const url = requireString(body, 'url', '远端地址');
979
+ const { runner, secrets } = await runnerAndSecrets();
980
+ const name = optionalString(body.name) ?? 'origin';
981
+ // The contract asks this route to resolve owner/repo for a GitHub URL. The
982
+ // response may only carry `output`, so the resolution is used for the one
983
+ // thing it can do here: reject a GitHub URL that names no repository
984
+ // (`https://github.com/`, `https://github.com/owner`), which git would
985
+ // otherwise store happily and every later push would fail against.
986
+ if (isGithubUrl(url) && parseGithubRemote(url) === null) {
987
+ throw httpError(400, 'BAD_REQUEST', `无法从 ${url} 解析出 GitHub 仓库(需要 owner/repo 两段)。`);
988
+ }
989
+ const result = await runner.setRemote(path, { name, url, secrets });
990
+ return { output: result.output };
991
+ }
992
+
993
+ /**
994
+ * `POST /local/fetch`.
995
+ * @param {object} body
996
+ * @returns {Promise<{output: string}>}
997
+ */
998
+ async function localFetch(body) {
999
+ const path = requireString(body, 'path', '仓库路径');
1000
+ const { settings, runner, secrets } = await runnerAndSecrets();
1001
+ const remote = pickRemote(body.remote, settings.defaultRemote);
1002
+ const token = await tokenForRemote(runner, path, remote);
1003
+ const result = await runner.fetch(path, {
1004
+ remote,
1005
+ prune: optionalBool(body.prune, false),
1006
+ token,
1007
+ secrets,
1008
+ });
1009
+ return { output: result.output };
1010
+ }
1011
+
1012
+ /**
1013
+ * `POST /local/pull`.
1014
+ * @param {object} body
1015
+ * @returns {Promise<{output: string}>}
1016
+ */
1017
+ async function localPull(body) {
1018
+ const path = requireString(body, 'path', '仓库路径');
1019
+ const { settings, runner, secrets } = await runnerAndSecrets();
1020
+ const remote = pickRemote(body.remote, settings.defaultRemote);
1021
+ const token = await tokenForRemote(runner, path, remote);
1022
+ const result = await runner.pull(path, {
1023
+ remote,
1024
+ branch: optionalString(body.branch),
1025
+ rebase: optionalBool(body.rebase, false),
1026
+ token,
1027
+ secrets,
1028
+ });
1029
+ return { output: result.output };
1030
+ }
1031
+
1032
+ /**
1033
+ * `POST /local/push` — CONTRACT §3b aware.
1034
+ *
1035
+ * DESTINATION RESOLUTION (in order, the first one that applies wins):
1036
+ *
1037
+ * 1. `target: {owner, repo}` — an existing remote that already points at
1038
+ * that repository is REUSED (so `.git/config` is untouched AND the push
1039
+ * gets the remote's own refspec/upstream behaviour); otherwise the push
1040
+ * goes straight to the constructed https URL. The URL form is the
1041
+ * contract's "never pollute the user's .git/config" rule; the token
1042
+ * rides along as a per-invocation header and is never written anywhere.
1043
+ * 2. `remote: '<name>'` — the pre-§3b behaviour, unchanged.
1044
+ * 3. Neither → the remembered target for this branch, then
1045
+ * `settings.defaultRemote`, then `origin`.
1046
+ *
1047
+ * MEMORY: only a SUCCESSFUL push is recorded, and `remember: false` opts out.
1048
+ * The key is `(normalizedRepoRoot, branch)` — see store.js.
1049
+ *
1050
+ * @param {object} body
1051
+ * @returns {Promise<{output: string}>}
1052
+ */
1053
+ async function localPush(body) {
1054
+ const path = requireString(body, 'path', '仓库路径');
1055
+ const { settings, runner, secrets } = await runnerAndSecrets();
1056
+
1057
+ // The root is resolved ONCE and reused: `assertRepo` costs three git spawns
1058
+ // and every helper below would otherwise repeat it.
1059
+ const root = (await runner.assertRepo(path, { secrets })).root;
1060
+ // The branch is needed THREE times here (memory lookup, refspec, memory
1061
+ // write), so it is resolved once. An explicit body.branch wins; otherwise
1062
+ // the branch HEAD points at; a detached HEAD leaves it null.
1063
+ const requestedBranch = optionalString(body.branch);
1064
+ const branch = requestedBranch ?? (await runner.currentBranch(path, { secrets, root }));
1065
+
1066
+ const target = await resolvePushTarget({
1067
+ runner,
1068
+ path,
1069
+ root,
1070
+ branch,
1071
+ settings,
1072
+ body,
1073
+ secrets,
1074
+ });
1075
+
1076
+ // A URL push has no configured merge ref, so it NEEDS an explicit refspec.
1077
+ // With a detached HEAD and no `branch` there is no name to push, and git's
1078
+ // own error ("You are not currently on a branch") arrives only after the
1079
+ // network handshake — failing here is faster and says what to do.
1080
+ if (target.url !== undefined && branch === null && requestedBranch === undefined) {
1081
+ throw httpError(
1082
+ 400,
1083
+ 'BAD_REQUEST',
1084
+ '当前处于分离 HEAD 状态,直接推送到 GitHub 仓库需要指定分支名(branch)。',
1085
+ );
1086
+ }
1087
+
1088
+ const result = await runner.push(path, {
1089
+ remote: target.url === undefined ? target.remote : undefined,
1090
+ url: target.url,
1091
+ // NAMED REMOTE: the body's branch, exactly as before — omitting it lets
1092
+ // git apply `push.default`/the configured upstream, which is the
1093
+ // behaviour the existing route has always had.
1094
+ // URL: a URL has no configured merge ref, so the RESOLVED branch (the
1095
+ // body's value, else the branch HEAD points at) must be sent as the
1096
+ // refspec; otherwise `git push <url>` has nothing to push.
1097
+ branch: target.url === undefined ? requestedBranch : (branch ?? undefined),
1098
+ // WHAT LEAVES the repository. Defaults to the branch, but the panel may
1099
+ // ask for a specific version — a commit sha or a tag — which git accepts
1100
+ // as a push source as long as a destination branch is named with it.
1101
+ source: optionalString(body.source),
1102
+ force: optionalBool(body.force, false),
1103
+ setUpstream: optionalBool(body.setUpstream, true),
1104
+ tags: optionalBool(body.tags, false),
1105
+ token: target.token,
1106
+ secrets,
1107
+ });
1108
+
1109
+ // Recorded only after the push actually succeeded: a failed push must not
1110
+ // change what the next click defaults to.
1111
+ if (optionalBool(body.remember, true) !== false) {
1112
+ try {
1113
+ await store.rememberPushTarget(root, branch, {
1114
+ remote: target.remote,
1115
+ owner: target.owner,
1116
+ repo: target.repo,
1117
+ ref: branch ?? '',
1118
+ at: new Date().toISOString(),
1119
+ });
1120
+ } catch {
1121
+ // Bookkeeping must never fail a push the user just completed.
1122
+ }
1123
+ }
1124
+ return { output: result.output };
1125
+ }
1126
+
1127
+ /**
1128
+ * Decide WHERE and WITH WHICH CREDENTIAL one `/local/push` should go.
1129
+ *
1130
+ * Split out of {@link localPush} because the decision has four inputs and two
1131
+ * outputs (destination + token) and is the whole point of CONTRACT §3b.
1132
+ *
1133
+ * @param {object} options
1134
+ * @returns {Promise<{remote: string, url?: string, token?: string,
1135
+ * owner: string, repo: string}>}
1136
+ */
1137
+ async function resolvePushTarget({ runner, path, root, branch, settings, body, secrets }) {
1138
+ const target = body.target && typeof body.target === 'object' ? body.target : null;
1139
+
1140
+ /* 1. An explicit GitHub repository. */
1141
+ if (target) {
1142
+ const owner = requireString(target, 'owner', '目标仓库的 owner');
1143
+ const repo = requireString(target, 'repo', '目标仓库名称');
1144
+ // Reuse a remote that ALREADY points at this repository. Matching is
1145
+ // case-insensitive because GitHub owners/repos are.
1146
+ const matched = await remoteForRepo(runner, path, owner, repo, secrets);
1147
+ if (matched) {
1148
+ // The reused remote keeps ITS OWN transport: an ssh remote gets no
1149
+ // token (and needs no account), an https one gets the header.
1150
+ const token = await tokenForRemote(runner, path, matched.name);
1151
+ return { remote: matched.name, token, owner, repo };
1152
+ }
1153
+ // No remote → push to the URL directly. `x-access-token` is the
1154
+ // documented https username; the TOKEN itself is never part of the URL
1155
+ // (it would leak through argv, git's error output and any proxy log).
1156
+ const token = await githubHttpsToken(`目标仓库 ${owner}/${repo}`);
1157
+ return { remote: '', url: githubPushUrl(owner, repo), token, owner, repo };
1158
+ }
1159
+
1160
+ /* 2. A named remote. */
1161
+ const explicitRemote = optionalString(body.remote);
1162
+ if (explicitRemote !== undefined) {
1163
+ const token = await tokenForRemote(runner, path, explicitRemote);
1164
+ const parsed = await remoteRepo(runner, path, explicitRemote, secrets);
1165
+ return {
1166
+ remote: explicitRemote,
1167
+ token,
1168
+ owner: parsed?.owner ?? '',
1169
+ repo: parsed?.repo ?? '',
1170
+ };
1171
+ }
1172
+
1173
+ /* 3a. The remembered target for THIS branch. */
1174
+ if (branch !== null) {
1175
+ const memory = await store.pushMemoryFor(root, branch);
1176
+ if (memory) {
1177
+ const remotes = await safeRemotes(runner, path, secrets);
1178
+ // A remembered remote may have been renamed or removed since; only
1179
+ // reuse it when it still exists, otherwise fall back to the URL that
1180
+ // was recorded (it is derived from owner/repo, so nothing is lost).
1181
+ const stillThere = memory.remote !== '' && remotes.some((row) => row.name === memory.remote);
1182
+ if (stillThere) {
1183
+ const token = await tokenForRemote(runner, path, memory.remote);
1184
+ return { remote: memory.remote, token, owner: memory.owner, repo: memory.repo };
1185
+ }
1186
+ if (memory.owner !== '' && memory.repo !== '') {
1187
+ // The remembered destination was a by-URL push, or its remote is
1188
+ // gone: go back to the same repository, still without touching the
1189
+ // configuration.
1190
+ const token = await githubHttpsToken(`记忆的目标仓库 ${memory.owner}/${memory.repo}`);
1191
+ return {
1192
+ remote: '',
1193
+ url: githubPushUrl(memory.owner, memory.repo),
1194
+ token,
1195
+ owner: memory.owner,
1196
+ repo: memory.repo,
1197
+ };
1198
+ }
1199
+ }
1200
+ }
1201
+
1202
+ /* 3b. `settings.defaultRemote`, then `origin`. */
1203
+ const remote = pickRemote(undefined, settings.defaultRemote);
1204
+ const token = await tokenForRemote(runner, path, remote);
1205
+ const parsed = await remoteRepo(runner, path, remote, secrets);
1206
+ return { remote, token, owner: parsed?.owner ?? '', repo: parsed?.repo ?? '' };
1207
+ }
1208
+
1209
+ /**
1210
+ * `git remote -v` as an array, or `[]` when the repository cannot answer.
1211
+ *
1212
+ * `secrets` is passed through so a remote URL that embeds a credential
1213
+ * (`https://user:TOKEN@github.com/…`, which a user can create by hand) is
1214
+ * scrubbed by the runner before it can reach `/push/targets`'s response.
1215
+ */
1216
+ async function safeRemotes(runner, path, secrets) {
1217
+ try {
1218
+ return (await runner.remotes(path, { secrets })).remotes;
1219
+ } catch {
1220
+ return [];
1221
+ }
1222
+ }
1223
+
1224
+ /** The `{owner, repo}` one named remote points at, or null. */
1225
+ async function remoteRepo(runner, path, remote, secrets) {
1226
+ const remotes = await safeRemotes(runner, path, secrets);
1227
+ const row = remotes.find((candidate) => candidate.name === remote);
1228
+ return row ? parseGithubRemote(row.url) : null;
1229
+ }
1230
+
1231
+ /**
1232
+ * The first remote whose GitHub URL names `owner/repo`, or null.
1233
+ *
1234
+ * Redaction does not break the match: it only masks the userinfo segment
1235
+ * (`https://***@github.com/o/r.git`), and `parseGithubRemote` reads the path.
1236
+ */
1237
+ async function remoteForRepo(runner, path, owner, repo, secrets) {
1238
+ const remotes = await safeRemotes(runner, path, secrets);
1239
+ for (const row of remotes) {
1240
+ const parsed = parseGithubRemote(row.url);
1241
+ if (!parsed) continue;
1242
+ if (parsed.owner.toLowerCase() === owner.toLowerCase()
1243
+ && parsed.repo.toLowerCase() === repo.toLowerCase()) {
1244
+ return row;
1245
+ }
1246
+ }
1247
+ return null;
1248
+ }
1249
+
1250
+ /**
1251
+ * `GET /push/targets` — the push-target picker's candidate document
1252
+ * (CONTRACT §3b).
1253
+ *
1254
+ * A directory that is not a repository answers the empty document instead of
1255
+ * failing: the picker is rendered next to the local-status panel, which is
1256
+ * routinely opened on a non-repository workspace.
1257
+ *
1258
+ * @param {{path: string}} query
1259
+ * @returns {Promise<object>}
1260
+ */
1261
+ async function pushTargets(query) {
1262
+ const path = requireString(query, 'path', '仓库路径');
1263
+ const { runner, secrets } = await runnerAndSecrets();
1264
+ let root;
1265
+ try {
1266
+ root = (await runner.assertRepo(path, { secrets })).root;
1267
+ } catch (error) {
1268
+ if (error?.code === 'NOT_A_REPO') {
1269
+ return { remotes: [], memory: null, branch: null, repoRoot: null };
1270
+ }
1271
+ throw error;
1272
+ }
1273
+ const [remotes, branch] = await Promise.all([
1274
+ safeRemotes(runner, path, secrets),
1275
+ runner.currentBranch(path, { secrets }),
1276
+ ]);
1277
+ const memory = branch === null ? null : await store.pushMemoryFor(root, branch);
1278
+ return {
1279
+ remotes: remotes.map((row) => {
1280
+ const parsed = parseGithubRemote(row.url);
1281
+ return {
1282
+ name: row.name,
1283
+ url: row.url,
1284
+ owner: parsed?.owner ?? null,
1285
+ repo: parsed?.repo ?? null,
1286
+ };
1287
+ }),
1288
+ memory,
1289
+ branch,
1290
+ repoRoot: root,
1291
+ };
1292
+ }
1293
+
1294
+ /**
1295
+ * `GET /push/remotes` — the picker's GitHub repository search (CONTRACT §3b).
1296
+ *
1297
+ * Deliberately a SEPARATE mapper from `/repos`: the picker only needs enough
1298
+ * to build a push destination, and reusing the full `RemoteRepo` shape here
1299
+ * would send permissions/avatars the picker never draws.
1300
+ *
1301
+ * @param {{q?: string, page?: string|number}} query
1302
+ * @returns {Promise<{items: object[], page: number, hasMore: boolean}>}
1303
+ */
1304
+ async function pushRemotes(query) {
1305
+ const account = await requireAccount();
1306
+ const page = clampInt(query.page, 1, 1000, 1);
1307
+ const q = optionalString(query.q);
1308
+ const result = q
1309
+ ? await searchRepos({ token: account.token, login: account.login, q, page })
1310
+ : await listRepos({ token: account.token, page });
1311
+ await touch(account.id);
1312
+ return {
1313
+ items: result.items.map((repo) => ({
1314
+ fullName: repo.fullName,
1315
+ owner: repo.owner,
1316
+ name: repo.name,
1317
+ private: repo.private,
1318
+ defaultBranch: repo.defaultBranch,
1319
+ cloneUrl: repo.cloneUrl,
1320
+ sshUrl: repo.sshUrl,
1321
+ htmlUrl: repo.htmlUrl,
1322
+ })),
1323
+ page: result.page,
1324
+ hasMore: result.hasMore,
1325
+ };
1326
+ }
1327
+
1328
+ /**
1329
+ * `GET /push/memory` — every remembered target for one repository
1330
+ * (CONTRACT §3b, debug view).
1331
+ *
1332
+ * @param {{path: string}} query
1333
+ * @returns {Promise<{entries: object[]}>}
1334
+ */
1335
+ async function pushMemory(query) {
1336
+ const path = requireString(query, 'path', '仓库路径');
1337
+ const { runner, secrets } = await runnerAndSecrets();
1338
+ let root;
1339
+ try {
1340
+ root = (await runner.assertRepo(path, { secrets })).root;
1341
+ } catch (error) {
1342
+ if (error?.code === 'NOT_A_REPO') return { entries: [] };
1343
+ throw error;
1344
+ }
1345
+ return { entries: await store.pushMemoryEntries(root) };
1346
+ }
1347
+
1348
+ /**
1349
+ * `POST /local/push/target/forget` — drop one branch's remembered target.
1350
+ *
1351
+ * Not in CONTRACT §3b's table, and OPTIONAL for the client: it exists because
1352
+ * a remembered target that has become wrong (pushed to the wrong fork once)
1353
+ * would otherwise be permanent from inside the panel.
1354
+ *
1355
+ * @param {object} body
1356
+ * @returns {Promise<{forgotten: boolean}>}
1357
+ */
1358
+ async function localForgetPushTarget(body) {
1359
+ const path = requireString(body, 'path', '仓库路径');
1360
+ const { runner, secrets } = await runnerAndSecrets();
1361
+ const root = (await runner.assertRepo(path, { secrets })).root;
1362
+ const branch = optionalString(body.branch)
1363
+ ?? (await runner.currentBranch(path, { secrets }));
1364
+ if (branch === null) throw httpError(400, 'BAD_REQUEST', '当前处于分离 HEAD 状态,请指定分支名');
1365
+ return { forgotten: await store.forgetPushTarget(root, branch) };
1366
+ }
1367
+
1368
+ /**
1369
+ * `POST /local/commit`.
1370
+ * @param {object} body
1371
+ * @returns {Promise<{output: string}>}
1372
+ */
1373
+ async function localCommit(body) {
1374
+ const path = requireString(body, 'path', '仓库路径');
1375
+ const message = requireString(body, 'message', '提交信息');
1376
+ const { runner, secrets } = await runnerAndSecrets();
1377
+ const files = Array.isArray(body.files)
1378
+ ? body.files.filter((file) => typeof file === 'string' && file !== '')
1379
+ : undefined;
1380
+ const result = await runner.commit(path, {
1381
+ message,
1382
+ all: optionalBool(body.all, true),
1383
+ files,
1384
+ secrets,
1385
+ });
1386
+ return { output: result.output };
1387
+ }
1388
+
1389
+ /**
1390
+ * `POST /local/checkout`.
1391
+ * @param {object} body
1392
+ * @returns {Promise<{output: string}>}
1393
+ */
1394
+ async function localCheckout(body) {
1395
+ const path = requireString(body, 'path', '仓库路径');
1396
+ const ref = requireString(body, 'ref', '要切换的分支或提交');
1397
+ const { runner, secrets } = await runnerAndSecrets();
1398
+ const result = await runner.checkout(path, {
1399
+ ref,
1400
+ create: optionalBool(body.create, false),
1401
+ secrets,
1402
+ });
1403
+ return { output: result.output };
1404
+ }
1405
+
1406
+ /**
1407
+ * `POST /local/branch`.
1408
+ * @param {object} body
1409
+ * @returns {Promise<{output: string}>}
1410
+ */
1411
+ async function localBranch(body) {
1412
+ const path = requireString(body, 'path', '仓库路径');
1413
+ const name = requireString(body, 'name', '分支名');
1414
+ const { runner, secrets } = await runnerAndSecrets();
1415
+ const result = await runner.createBranch(path, {
1416
+ name,
1417
+ from: optionalString(body.from),
1418
+ checkout: optionalBool(body.checkout, true),
1419
+ secrets,
1420
+ });
1421
+ return { output: result.output };
1422
+ }
1423
+
1424
+ /**
1425
+ * `POST /local/branch/delete`.
1426
+ * @param {object} body
1427
+ * @returns {Promise<{output: string}>}
1428
+ */
1429
+ async function localBranchDelete(body) {
1430
+ const path = requireString(body, 'path', '仓库路径');
1431
+ const name = requireString(body, 'name', '分支名');
1432
+ const { runner, secrets } = await runnerAndSecrets();
1433
+ const result = await runner.deleteBranch(path, {
1434
+ name,
1435
+ force: optionalBool(body.force, false),
1436
+ secrets,
1437
+ });
1438
+ return { output: result.output };
1439
+ }
1440
+
1441
+ /**
1442
+ * `POST /local/merge`.
1443
+ * @param {object} body
1444
+ * @returns {Promise<{output: string}>}
1445
+ */
1446
+ async function localMerge(body) {
1447
+ const path = requireString(body, 'path', '仓库路径');
1448
+ const ref = requireString(body, 'ref', '要合并的分支或提交');
1449
+ const { runner, secrets } = await runnerAndSecrets();
1450
+ const result = await runner.merge(path, { ref, secrets });
1451
+ return { output: result.output };
1452
+ }
1453
+
1454
+ /**
1455
+ * `POST /local/reset` — `mode: 'hard'` is destructive, so it needs `confirm`.
1456
+ * @param {object} body
1457
+ * @returns {Promise<{output: string}>}
1458
+ */
1459
+ async function localReset(body) {
1460
+ const path = requireString(body, 'path', '仓库路径');
1461
+ const mode = body.mode === 'soft' || body.mode === 'hard' ? body.mode : 'mixed';
1462
+ if (mode === 'hard' && optionalBool(body.confirm, false) !== true) {
1463
+ throw httpError(409, 'CONFLICT', '硬重置会永久丢弃所有未提交的改动,请确认后再执行(confirm: true)。');
1464
+ }
1465
+ const { runner, secrets } = await runnerAndSecrets();
1466
+ const result = await runner.reset(path, {
1467
+ ref: optionalString(body.ref) ?? 'HEAD',
1468
+ mode,
1469
+ secrets,
1470
+ });
1471
+ return { output: result.output };
1472
+ }
1473
+
1474
+ /**
1475
+ * `POST /local/revert` and `POST /local/revert-commit`.
1476
+ *
1477
+ * Both routes undo one commit by REVERTING it (a new commit), never by
1478
+ * rewinding history: the contract's two rows describe the same undo, and the
1479
+ * non-destructive form is the one that cannot lose already-pushed work.
1480
+ * @param {object} body
1481
+ * @returns {Promise<{output: string}>}
1482
+ */
1483
+ async function localRevert(body) {
1484
+ const path = requireString(body, 'path', '仓库路径');
1485
+ const sha = requireString(body, 'sha', '提交 SHA');
1486
+ const { runner, secrets } = await runnerAndSecrets();
1487
+ const result = await runner.revert(path, { sha, secrets });
1488
+ return { output: result.output };
1489
+ }
1490
+
1491
+ /**
1492
+ * `POST /local/tag`.
1493
+ * @param {object} body
1494
+ * @returns {Promise<{output: string}>}
1495
+ */
1496
+ async function localTag(body) {
1497
+ const path = requireString(body, 'path', '仓库路径');
1498
+ const name = requireString(body, 'name', '标签名');
1499
+ const { settings, runner, secrets } = await runnerAndSecrets();
1500
+ const remote = pickRemote(body.remote, settings.defaultRemote);
1501
+ const wantsPush = optionalBool(body.push, false);
1502
+ const token = wantsPush ? await tokenForRemote(runner, path, remote) : undefined;
1503
+ const result = await runner.tag(path, {
1504
+ name,
1505
+ ref: optionalString(body.ref) ?? 'HEAD',
1506
+ push: wantsPush,
1507
+ remote,
1508
+ token,
1509
+ secrets,
1510
+ });
1511
+ return { output: result.output };
1512
+ }
1513
+
1514
+ /**
1515
+ * `POST /local/stash`.
1516
+ * @param {object} body
1517
+ * @returns {Promise<{output: string}>}
1518
+ */
1519
+ async function localStash(body) {
1520
+ const path = requireString(body, 'path', '仓库路径');
1521
+ const { runner, secrets } = await runnerAndSecrets();
1522
+ const result = await runner.stash(path, {
1523
+ message: optionalString(body.message),
1524
+ includeUntracked: optionalBool(body.includeUntracked, true),
1525
+ secrets,
1526
+ });
1527
+ return { output: result.output };
1528
+ }
1529
+
1530
+ /**
1531
+ * `POST /local/stash/pop`.
1532
+ * @param {object} body
1533
+ * @returns {Promise<{output: string}>}
1534
+ */
1535
+ async function localStashPop(body) {
1536
+ const path = requireString(body, 'path', '仓库路径');
1537
+ const { runner, secrets } = await runnerAndSecrets();
1538
+ const result = await runner.stashPop(path, {
1539
+ index: clampInt(body.index, 0, 999, 0),
1540
+ secrets,
1541
+ });
1542
+ return { output: result.output };
1543
+ }
1544
+
1545
+ /**
1546
+ * `POST /local/restore`.
1547
+ * @param {object} body
1548
+ * @returns {Promise<{output: string}>}
1549
+ */
1550
+ async function localRestore(body) {
1551
+ const path = requireString(body, 'path', '仓库路径');
1552
+ const files = Array.isArray(body.files) ? body.files : [];
1553
+ if (files.length === 0) throw httpError(400, 'BAD_REQUEST', '缺少要还原的文件');
1554
+ const { runner, secrets } = await runnerAndSecrets();
1555
+ const result = await runner.restore(path, {
1556
+ files,
1557
+ staged: optionalBool(body.staged, false),
1558
+ secrets,
1559
+ });
1560
+ return { output: result.output };
1561
+ }
1562
+
1563
+ /**
1564
+ * `POST /local/discard-all` — destructive; requires `confirm: true`.
1565
+ * @param {object} body
1566
+ * @returns {Promise<{output: string}>}
1567
+ */
1568
+ async function localDiscardAll(body) {
1569
+ const path = requireString(body, 'path', '仓库路径');
1570
+ if (optionalBool(body.confirm, false) !== true) {
1571
+ throw httpError(409, 'CONFLICT', '丢弃全部改动会永久删除所有未提交内容(含未跟踪文件),请确认后再执行(confirm: true)。');
1572
+ }
1573
+ const { runner, secrets } = await runnerAndSecrets();
1574
+ const result = await runner.discardAll(path, { secrets });
1575
+ return { output: result.output };
1576
+ }
1577
+
1578
+ /**
1579
+ * Which repository a tool-initiated release should land in.
1580
+ *
1581
+ * An explicit owner/repo wins; otherwise the working directory's own GitHub
1582
+ * remote decides, because "publish this checkout" is what the caller means.
1583
+ * Guessing a repository would be worse than failing, so an unattached
1584
+ * directory gets a clear instruction instead.
1585
+ *
1586
+ * @param {string} path repository path.
1587
+ * @param {object} args tool arguments (`owner`, `repo`).
1588
+ * @returns {Promise<{owner: string, repo: string}>}
1589
+ */
1590
+ async function toolReleaseTarget(path, args) {
1591
+ const explicitOwner = optionalString(args?.owner);
1592
+ const explicitRepo = optionalString(args?.repo);
1593
+ if (explicitOwner && explicitRepo) return { owner: explicitOwner, repo: explicitRepo };
1594
+ const status = await localStatus(path);
1595
+ if (!status.isRepo) {
1596
+ throw httpError(400, 'NOT_A_REPO', `${status.root ?? path} 不是 Git 仓库,无法推断要发布到哪个仓库。`);
1597
+ }
1598
+ if (status.githubRemote && status.githubRemote.owner && status.githubRemote.repo) {
1599
+ return { owner: status.githubRemote.owner, repo: status.githubRemote.repo };
1600
+ }
1601
+ throw httpError(
1602
+ 400,
1603
+ 'BAD_REQUEST',
1604
+ '当前工作区没有关联 GitHub 远端,无法推断要发布到哪个仓库;请传 owner 与 repo,或先用 /local/remote 关联远端。',
1605
+ );
1606
+ }
1607
+
1608
+ /**
1609
+ * `GET /repos/languages` — the byte/percentage breakdown the cards bar uses.
1610
+ *
1611
+ * A failure here must not break a repository list, so a scope or network
1612
+ * problem degrades to an empty list with a warning rather than an error.
1613
+ *
1614
+ * @param {{owner: string, name: string}} query
1615
+ * @returns {Promise<{items: object[]}>}
1616
+ */
1617
+ async function repoLanguages(query) {
1618
+ const account = await requireAccount();
1619
+ const owner = requireString(query, 'owner', ' owner');
1620
+ const name = requireString(query, 'name', ' name');
1621
+ try {
1622
+ const result = await repoLanguages({ token: account.token, owner, name });
1623
+ await touch(account.id);
1624
+ return result;
1625
+ } catch (error) {
1626
+ // Degrade: the card simply renders without the language bar.
1627
+ if (error && (error.code === 'UNAUTHORIZED' || error.code === 'NOT_FOUND')) {
1628
+ return { items: [], warning: '无法读取语言构成(权限或仓库不可见)。' };
1629
+ }
1630
+ throw error;
1631
+ }
1632
+ }
1633
+
1634
+ /**
1635
+ * `POST /releases/asset/delete` — remove one uploaded asset.
1636
+ *
1637
+ * @param {object} body
1638
+ * @returns {Promise<{deleted: true}>}
1639
+ */
1640
+ async function releaseAssetDelete(body) {
1641
+ const account = await requireAccount();
1642
+ const owner = requireString(body, 'owner', ' owner');
1643
+ const name = requireString(body, 'name', '仓库名称');
1644
+ const assetId = requireString(body, 'assetId', '附件 id');
1645
+ const result = await deleteReleaseAsset({
1646
+ token: account.token,
1647
+ owner,
1648
+ name,
1649
+ assetId,
1650
+ });
1651
+ await touch(account.id);
1652
+ return result;
1653
+ }
1654
+
1655
+ /**
1656
+ * `POST /releases/asset` — attach a file to a release.
1657
+ *
1658
+ * The body carries base64 because the transport is JSON. Uploads are the one
1659
+ * place where a size cap matters: GitHub rejects assets over 2 GB, and
1660
+ * buffering an arbitrary file in memory would be worse, so the cap is applied
1661
+ * here with a Chinese explanation.
1662
+ *
1663
+ * @param {object} body
1664
+ * @returns {Promise<{asset: object}>}
1665
+ */
1666
+ async function releaseAssetUpload(body) {
1667
+ const account = await requireAccount();
1668
+ const owner = requireString(body, 'owner', ' owner');
1669
+ const name = requireString(body, 'name', '仓库名称');
1670
+ const releaseId = requireString(body, 'releaseId', '发布 id');
1671
+ const fileName = requireString(body, 'fileName', '文件名');
1672
+ const base64 = requireString(body, 'base64', '文件内容');
1673
+ const bytes = Buffer.from(base64, 'base64');
1674
+ if (bytes.length === 0) throw httpError(400, 'BAD_REQUEST', '文件内容为空。');
1675
+ const MAX_BYTES = 200 * 1024 * 1024;
1676
+ if (bytes.length > MAX_BYTES) {
1677
+ throw httpError(
1678
+ 400,
1679
+ 'BAD_REQUEST',
1680
+ `附件超过 ${MAX_BYTES / 1024 / 1024} MB,请改用更小的文件或分卷发布。`,
1681
+ );
1682
+ }
1683
+ const result = await uploadReleaseAsset({
1684
+ token: account.token,
1685
+ owner,
1686
+ name,
1687
+ releaseId,
1688
+ fileName,
1689
+ bytes,
1690
+ contentType: optionalString(body.contentType),
1691
+ });
1692
+ await touch(account.id);
1693
+ return result;
1694
+ }
1695
+
1696
+ /* ─────────────────────── 平台自有的 state / settings ─────────────────── */
1697
+
1698
+ /**
1699
+ * 审查与 Git 状态。客户端靠它渲染设置页与判定"能不能用 git"。
1700
+ *
1701
+ * 内核也有 `/state`,但它不认识 git 二进制——那属于本平台。所以本平台
1702
+ * 自己提供一份,多带 `gitAvailable` / `gitVersion` 两个字段。
1703
+ *
1704
+ * @returns {Promise<object>}
1705
+ */
1706
+ async function stateLocal() {
1707
+ const [doc, probe] = await Promise.all([store.read(), probeGit()]);
1708
+ return {
1709
+ accounts: doc.accounts.map((account) => ({
1710
+ id: String(account.id ?? ''),
1711
+ login: String(account.login ?? ''),
1712
+ name: account.name ?? null,
1713
+ avatarUrl: account.avatarUrl ?? null,
1714
+ htmlUrl: account.htmlUrl ?? null,
1715
+ tokenKind: account.tokenKind === 'oauth' ? 'oauth' : 'pat',
1716
+ scopes: Array.isArray(account.scopes) ? account.scopes : [],
1717
+ addedAt: typeof account.addedAt === 'string' ? account.addedAt : new Date(0).toISOString(),
1718
+ lastUsedAt: typeof account.lastUsedAt === 'string' ? account.lastUsedAt : null,
1719
+ })),
1720
+ activeAccountId: doc.activeAccountId,
1721
+ settings: { ...doc.settings },
1722
+ gitAvailable: probe.available,
1723
+ gitVersion: probe.version,
1724
+ };
1725
+ }
1726
+
1727
+ /** 保存设置。只接受本平台关心的四个键。 */
1728
+ async function saveSettings(body) {
1729
+ const patch = {};
1730
+ if (body.oauthClientId !== undefined) {
1731
+ if (typeof body.oauthClientId !== 'string') {
1732
+ throw httpError(400, 'BAD_REQUEST', 'oauthClientId 必须是字符串');
1733
+ }
1734
+ patch.oauthClientId = body.oauthClientId.trim();
1735
+ }
1736
+ if (body.defaultRemote !== undefined) {
1737
+ if (typeof body.defaultRemote !== 'string') {
1738
+ throw httpError(400, 'BAD_REQUEST', 'defaultRemote 必须是字符串');
1739
+ }
1740
+ patch.defaultRemote = body.defaultRemote.trim() === '' ? 'origin' : body.defaultRemote.trim();
1741
+ }
1742
+ if (body.showPrivate !== undefined) {
1743
+ if (typeof body.showPrivate !== 'boolean') {
1744
+ throw httpError(400, 'BAD_REQUEST', 'showPrivate 必须是布尔值');
1745
+ }
1746
+ patch.showPrivate = body.showPrivate;
1747
+ }
1748
+ if (body.gitPath !== undefined) {
1749
+ if (typeof body.gitPath !== 'string') {
1750
+ throw httpError(400, 'BAD_REQUEST', 'gitPath 必须是字符串');
1751
+ }
1752
+ patch.gitPath = body.gitPath.trim();
1753
+ }
1754
+ const settings = await store.updateSettings(patch);
1755
+ // 改了 git 路径要让下次探测重新跑。
1756
+ gitProbeCache = null;
1757
+ gitProbeAt = 0;
1758
+ return { settings };
1759
+ }
1760
+
1761
+ /* ─────────────────────────── 路由表 ──────────────────────────────────── */
1762
+
1763
+ const route = (path, method, run) => ({ path, method, run });
1764
+
1765
+ const GITHUB_ROUTES = [
1766
+ /* 状态与设置(本平台自带,多带 git 探测结果) */
1767
+ route('/state', 'GET', async () => stateLocal()),
1768
+ route('/settings', 'POST', async ({ body }) => saveSettings(body)),
1769
+
1770
+ /* 账号 */
1771
+ route('/accounts/token', 'POST', async ({ body }) => addTokenAccount(body)),
1772
+ route('/accounts/device/start', 'POST', async () => deviceStart()),
1773
+ route('/accounts/device/poll', 'POST', async ({ body }) => devicePoll(body)),
1774
+ route('/accounts/activate', 'POST', async ({ body }) => activateAccount(body)),
1775
+ route('/accounts/remove', 'POST', async ({ body }) => removeAccount(body)),
1776
+
1777
+ /* 仓库 */
1778
+ route('/repos', 'GET', async ({ query }) => repos({
1779
+ page: query('page'),
1780
+ q: query('q'),
1781
+ })),
1782
+ route('/repos/detail', 'GET', async ({ query }) => repoDetail({
1783
+ owner: query('owner'),
1784
+ name: query('name'),
1785
+ })),
1786
+ route('/repos/create', 'POST', async ({ body }) => repoCreate(body)),
1787
+ route('/repos/delete', 'POST', async ({ body }) => repoDelete(body)),
1788
+ route('/repos/languages', 'GET', async ({ query }) => repoLanguages({
1789
+ owner: query('owner'),
1790
+ name: query('name'),
1791
+ })),
1792
+ route('/repos/manage', 'GET', async ({ query }) => repoManage({
1793
+ owner: query('owner'),
1794
+ name: query('name'),
1795
+ })),
1796
+ route('/repos/update', 'POST', async ({ body }) => repoUpdate(body)),
1797
+ route('/repos/branch/rename', 'POST', async ({ body }) => repoBranchRename(body)),
1798
+ route('/repos/branch/delete', 'POST', async ({ body }) => repoBranchDelete(body)),
1799
+ route('/repos/branch/protect', 'POST', async ({ body }) => repoBranchProtect(body)),
1800
+ route('/repos/release/delete', 'POST', async ({ body }) => repoReleaseDelete(body)),
1801
+ route('/repos/release/update', 'POST', async ({ body }) => repoReleaseUpdate(body)),
1802
+ route('/repos/collaborator/add', 'POST', async ({ body }) => repoCollaboratorAdd(body)),
1803
+ route('/repos/collaborator/remove', 'POST', async ({ body }) => repoCollaboratorRemove(body)),
1804
+ route('/repos/rename', 'POST', async ({ body }) => repoRename(body)),
1805
+ route('/repos/transfer', 'POST', async ({ body }) => repoTransfer(body)),
1806
+
1807
+ /* 发布 */
1808
+ route('/releases', 'GET', async ({ query }) => releases({
1809
+ owner: query('owner'),
1810
+ repo: query('repo'),
1811
+ })),
1812
+ route('/releases', 'POST', async ({ body }) => releaseCreate(body)),
1813
+ route('/releases/asset', 'POST', async ({ body }) => releaseAssetUpload(body)),
1814
+ route('/releases/asset/delete', 'POST', async ({ body }) => releaseAssetDelete(body)),
1815
+
1816
+ /* 活动 */
1817
+ route('/contributions', 'GET', async ({ query }) => contributions({
1818
+ owner: query('owner'),
1819
+ })),
1820
+ route('/notifications', 'GET', async ({ query }) => notifications({
1821
+ all: query('all'),
1822
+ })),
1823
+ route('/notifications/read', 'POST', async ({ body }) => notificationRead(body)),
1824
+
1825
+ /* 本地 Git */
1826
+ route('/local/status', 'GET', async ({ query }) => localStatus(query('path'))),
1827
+ route('/local/log', 'GET', async ({ query }) => localLog({
1828
+ path: query('path'),
1829
+ limit: query('limit'),
1830
+ })),
1831
+ route('/local/diff', 'GET', async ({ query }) => localDiff({
1832
+ path: query('path'),
1833
+ file: query('file'),
1834
+ staged: query('staged') === 'true',
1835
+ })),
1836
+ route('/local/commit', 'GET', async ({ query }) => localCommitDetail({
1837
+ path: query('path'),
1838
+ sha: query('sha'),
1839
+ })),
1840
+ route('/local/remotes', 'GET', async ({ query }) => localRemotes({ path: query('path') })),
1841
+ route('/local/init', 'POST', async ({ body }) => localInit(body)),
1842
+ route('/local/remote', 'POST', async ({ body }) => localSetRemote(body)),
1843
+ route('/local/fetch', 'POST', async ({ body }) => localFetch(body)),
1844
+ route('/local/pull', 'POST', async ({ body }) => localPull(body)),
1845
+ route('/local/push', 'POST', async ({ body }) => localPush(body)),
1846
+ route('/local/push/target/forget', 'POST', async ({ body }) => localForgetPushTarget(body)),
1847
+ route('/local/commit', 'POST', async ({ body }) => localCommit(body)),
1848
+ route('/local/checkout', 'POST', async ({ body }) => localCheckout(body)),
1849
+ route('/local/branch', 'POST', async ({ body }) => localBranch(body)),
1850
+ route('/local/branch/delete', 'POST', async ({ body }) => localBranchDelete(body)),
1851
+ route('/local/merge', 'POST', async ({ body }) => localMerge(body)),
1852
+ route('/local/reset', 'POST', async ({ body }) => localReset(body)),
1853
+ route('/local/revert', 'POST', async ({ body }) => localRevert(body)),
1854
+ route('/local/revert-commit', 'POST', async ({ body }) => localRevert(body)),
1855
+ route('/local/tag', 'POST', async ({ body }) => localTag(body)),
1856
+ route('/local/stash', 'POST', async ({ body }) => localStash(body)),
1857
+ route('/local/stash/pop', 'POST', async ({ body }) => localStashPop(body)),
1858
+ route('/local/restore', 'POST', async ({ body }) => localRestore(body)),
1859
+ route('/local/discard-all', 'POST', async ({ body }) => localDiscardAll(body)),
1860
+ route('/push/targets', 'GET', async ({ query }) => pushTargets({ path: query('path') })),
1861
+ route('/push/remotes', 'GET', async ({ query }) => pushRemotes({
1862
+ q: query('q'),
1863
+ page: query('page'),
1864
+ })),
1865
+ route('/push/memory', 'GET', async ({ query }) => pushMemory({ path: query('path') })),
1866
+ ];
1867
+
1868
+ /* ─────────────────────────── Agent 动作 ──────────────────────────────── */
1869
+
1870
+ /**
1871
+ * 给模型用的动作。
1872
+ *
1873
+ * 与界面走同一条代码路径(one operation, two callers):每个 action 只是
1874
+ * 把参数整理成对应方法的入参。
1875
+ */
1876
+ const GITHUB_ACTIONS = [
1877
+ {
1878
+ id: 'status',
1879
+ description: '查看目录的 Git 状态:分支、领先/落后、改动文件清单。',
1880
+ parameters: { path: { type: 'string', description: '目录绝对路径;省略则用当前会话目录' } },
1881
+ run: async (args, host) => {
1882
+ const dir = optionalString(args?.path) ?? process.cwd();
1883
+ return { status: await host.localStatus(dir) };
1884
+ },
1885
+ },
1886
+ {
1887
+ id: 'log',
1888
+ description: '读取提交历史(版本树数据)。',
1889
+ parameters: {
1890
+ path: { type: 'string', description: '仓库绝对路径' },
1891
+ limit: { type: 'number', description: '最多多少条,默认 60' },
1892
+ },
1893
+ run: async (args, host) => host.localLog({ path: optionalString(args?.path) ?? process.cwd(), limit: args?.limit }),
1894
+ },
1895
+ {
1896
+ id: 'push',
1897
+ description: '推送当前分支。可用 owner + repo 指定目标仓库。',
1898
+ parameters: {
1899
+ path: { type: 'string', description: '仓库绝对路径' },
1900
+ owner: { type: 'string', description: '目标仓库所有者(与 repo 一起用)' },
1901
+ repo: { type: 'string', description: '目标仓库名' },
1902
+ remote: { type: 'string', description: '远端名;省略则用设置里的默认远端' },
1903
+ branch: { type: 'string', description: '分支名' },
1904
+ force: { type: 'boolean', description: '是否强制推送' },
1905
+ },
1906
+ run: async (args, host) => {
1907
+ const owner = optionalString(args?.owner);
1908
+ const repo = optionalString(args?.repo);
1909
+ const target = owner && repo ? { owner, repo } : undefined;
1910
+ const result = await host.localPush({
1911
+ path: optionalString(args?.path) ?? process.cwd(),
1912
+ remote: target ? undefined : optionalString(args?.remote),
1913
+ target,
1914
+ branch: optionalString(args?.branch),
1915
+ force: optionalBool(args?.force, false),
1916
+ });
1917
+ return { output: result.output };
1918
+ },
1919
+ },
1920
+ {
1921
+ id: 'pull',
1922
+ description: '拉取远端更新。',
1923
+ parameters: {
1924
+ path: { type: 'string', description: '仓库绝对路径' },
1925
+ remote: { type: 'string', description: '远端名' },
1926
+ branch: { type: 'string', description: '分支名' },
1927
+ },
1928
+ run: async (args, host) => {
1929
+ const result = await host.localPull({
1930
+ path: optionalString(args?.path) ?? process.cwd(),
1931
+ remote: optionalString(args?.remote),
1932
+ branch: optionalString(args?.branch),
1933
+ });
1934
+ return { output: result.output };
1935
+ },
1936
+ },
1937
+ {
1938
+ id: 'commit',
1939
+ description: '提交所有改动。',
1940
+ parameters: {
1941
+ path: { type: 'string', description: '仓库绝对路径' },
1942
+ message: { type: 'string', description: '提交信息' },
1943
+ },
1944
+ run: async (args, host) => {
1945
+ const result = await host.localCommit({
1946
+ path: optionalString(args?.path) ?? process.cwd(),
1947
+ message: requireString(args, 'message', '提交信息'),
1948
+ all: true,
1949
+ });
1950
+ return { output: result.output };
1951
+ },
1952
+ },
1953
+ {
1954
+ id: 'repos',
1955
+ description: '列出当前账号的仓库(支持搜索)。',
1956
+ parameters: {
1957
+ q: { type: 'string', description: '搜索关键词' },
1958
+ page: { type: 'number', description: '页码' },
1959
+ },
1960
+ run: async (args, host) => {
1961
+ const result = await host.repos({ page: args?.page, q: optionalString(args?.q) });
1962
+ return {
1963
+ total: result.total,
1964
+ items: (result.items || []).map((repo) => ({
1965
+ fullName: repo.fullName,
1966
+ private: repo.private,
1967
+ defaultBranch: repo.defaultBranch,
1968
+ htmlUrl: repo.htmlUrl,
1969
+ })),
1970
+ };
1971
+ },
1972
+ },
1973
+ {
1974
+ id: 'accounts',
1975
+ description: '列出已登录的 GitHub 账号(不含令牌)。',
1976
+ run: async (_args, host) => {
1977
+ const state = await host.state();
1978
+ return { accounts: state.accounts, activeAccountId: state.activeAccountId };
1979
+ },
1980
+ },
1981
+ {
1982
+ id: 'create_repo',
1983
+ description: '新建仓库。',
1984
+ parameters: {
1985
+ name: { type: 'string', description: '仓库名' },
1986
+ private: { type: 'boolean', description: '是否私有' },
1987
+ description: { type: 'string', description: '仓库简介' },
1988
+ },
1989
+ run: async (args, host) => {
1990
+ const result = await host.repoCreate({
1991
+ name: requireString(args, 'name', '仓库名'),
1992
+ private: optionalBool(args?.private, true),
1993
+ description: optionalString(args?.description) ?? '',
1994
+ });
1995
+ return {
1996
+ owner: result.owner,
1997
+ name: result.name,
1998
+ htmlUrl: result.htmlUrl,
1999
+ cloneUrl: result.cloneUrl,
2000
+ };
2001
+ },
2002
+ },
2003
+ {
2004
+ id: 'release',
2005
+ description: '基于某个提交或标签创建 Release。',
2006
+ parameters: {
2007
+ path: { type: 'string', description: '仓库绝对路径' },
2008
+ tagName: { type: 'string', description: '标签名' },
2009
+ releaseName: { type: 'string', description: '发布标题(注意不是仓库名)' },
2010
+ body: { type: 'string', description: '发布说明' },
2011
+ draft: { type: 'boolean', description: '是否草稿' },
2012
+ },
2013
+ run: async (args, host, context) => {
2014
+ const dir = optionalString(args?.path) ?? process.cwd();
2015
+ const target = await toolReleaseTarget(dir, args);
2016
+ const result = await host.releaseCreate({
2017
+ path: dir,
2018
+ owner: target.owner,
2019
+ repo: target.repo,
2020
+ tagName: requireString(args, 'tagName', '标签名'),
2021
+ releaseName: optionalString(args?.releaseName),
2022
+ body: optionalString(args?.body) ?? '',
2023
+ draft: optionalBool(args?.draft, false),
2024
+ });
2025
+ return {
2026
+ id: result.release.id,
2027
+ tagName: result.release.tagName,
2028
+ name: result.release.name,
2029
+ draft: result.release.draft,
2030
+ htmlUrl: result.release.htmlUrl,
2031
+ };
2032
+ },
2033
+ },
2034
+ ];
2035
+
2036
+ /* ───────────────────────── 平台定义 ───────────────────────── */
2037
+
2038
+ return {
2039
+ id: 'github',
2040
+ label: 'GitHub',
2041
+ order: 10,
2042
+ icon: 'GithubMark',
2043
+
2044
+ host: {
2045
+ /* 状态与设置 */
2046
+ state: stateLocal,
2047
+ updateSettings: saveSettings,
2048
+ gitProbe: probeGit,
2049
+
2050
+ /* 账号 */
2051
+ addTokenAccount,
2052
+ deviceStart,
2053
+ devicePoll,
2054
+ activateAccount,
2055
+ removeAccount,
2056
+
2057
+ /* 仓库 */
2058
+ repos,
2059
+ repoDetail,
2060
+ repoCreate,
2061
+ repoDelete,
2062
+ repoManage,
2063
+ repoUpdate,
2064
+ repoBranchRename,
2065
+ repoBranchDelete,
2066
+ repoBranchProtect,
2067
+ repoReleaseDelete,
2068
+ repoReleaseUpdate,
2069
+ repoCollaboratorAdd,
2070
+ repoCollaboratorRemove,
2071
+ repoRename,
2072
+ repoTransfer,
2073
+ repoLanguages,
2074
+
2075
+ /* 发布 */
2076
+ releases,
2077
+ releaseCreate,
2078
+ releaseAssetUpload,
2079
+ releaseAssetDelete,
2080
+
2081
+ /* 活动 */
2082
+ contributions,
2083
+ notifications,
2084
+ notificationRead,
2085
+
2086
+ /* 本地 Git */
2087
+ localStatus,
2088
+ localLog,
2089
+ localDiff,
2090
+ localCommitDetail,
2091
+ localRemotes,
2092
+ localInit,
2093
+ localSetRemote,
2094
+ localFetch,
2095
+ localPull,
2096
+ localPush,
2097
+ localCommit,
2098
+ localCheckout,
2099
+ localBranch,
2100
+ localBranchDelete,
2101
+ localMerge,
2102
+ localReset,
2103
+ localRevert,
2104
+ localTag,
2105
+ localStash,
2106
+ localStashPop,
2107
+ localRestore,
2108
+ localDiscardAll,
2109
+ pushTargets,
2110
+ pushRemotes,
2111
+ pushMemory,
2112
+ localForgetPushTarget,
2113
+ },
2114
+
2115
+ routes: GITHUB_ROUTES,
2116
+ actions: GITHUB_ACTIONS,
2117
+ };
2118
+ }