dsh-session-superagent 0.9.176 → 0.9.178

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,81 @@
2
2
 
3
3
  格式参照 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
4
4
 
5
+ ## [0.9.178] - 2026-11-04 —— 用真实 Gitee 响应校对:编号是字符串,不是数字
6
+
7
+ ### 怎么发现的
8
+ 0.9.177 合入后拿**真实** Gitee API 跑了一遍(`oschina/git-osc`,公开仓库):
9
+
10
+ ```text
11
+ #IKMFKU | open | issue | 显示问题
12
+ #1 | closed | PR | test
13
+ ```
14
+
15
+ issue 的 `number` 是 **`"IKSQJH"` 这种字符串**(`id` 才是数字 34933085),PR 的 `number` 才是数字。
16
+
17
+ ### 原来错在哪
18
+ ```js
19
+ number: Number(item.number ?? item.id) || 0 // → NaN → 0
20
+ ```
21
+ 所有 Gitee issue 的编号都会变成 `0`:去重键相同(永远只有一条)、ack 打不中、唤醒消息里全是 `#0`。
22
+
23
+ ### 改法
24
+ - `normalizeGiteeItem`:编号**保持原样转字符串**,不再 `Number()`;
25
+ - `fetchGiteeLastComment` / `addGiteeLabel`:按原样拼 URL(`/issues/IKSQJH/comments`、`/pulls/14/comments`);
26
+ - `watch_ack`:编号不再强制 `Number()` —— 以前 Gitee 的字符串编号会被过滤成空数组,
27
+ 报「number is required」,看着像用户没填。
28
+
29
+ ### 真机联调结果
30
+ ```
31
+ listGiteeItems({ repo:'oschina/git-osc', perPage:5 })
32
+ → ok:true, partial:null, 10 条(issue + PR 混排,按 updated_at 倒序)
33
+ → #IKMFKU open issue 显示问题 / #1 closed PR test …
34
+ ```
35
+
36
+ ### 证据
37
+ ```
38
+ node --test → 285/285(新增 2 条:真机字符串编号 / 字符串编号也能拼出评论与标签 URL)
39
+ ```
40
+
41
+ ## [0.9.177] - 2026-11-04 —— 兼容 Gitee:同一个插件盯两家
42
+
43
+ ### 为什么
44
+ 客户要盯 `Ghandi/workbuddy-pro`(Gitee),而插件此前只认 `gh` CLI + `api.github.com`。
45
+
46
+ ### 怎么用(三种写法)
47
+ ```
48
+ owner/name # GitHub(默认)
49
+ gitee:owner/name # Gitee
50
+ https://gitee.com/owner/name # 直接粘地址栏(.git 结尾也行)
51
+ ```
52
+
53
+ ### 两家不一样的地方(只换域名会踩的坑)
54
+ | 维度 | GitHub | Gitee |
55
+ |---|---|---|
56
+ | 认证 | `gh` CLI / 面板 token | 私人令牌(设置里新增「Gitee 令牌」) |
57
+ | 状态值 | open / closed | 还有 `progressing` / `rejected`(rejected 才算关闭) |
58
+ | PR 列表 | `/issues` 里带 `pull_request` | 独立 `/pulls`,要合并 |
59
+ | 批量评论 | GraphQL 一次查多条 | 逐条 REST |
60
+ | 条件请求 | ETag → 304 不计额度 | **没有 ETag**,每轮全读 |
61
+
62
+ ### 实现(不复制判定逻辑)
63
+ - 新增 `lib/gitee.js`:请求 / 归一化 / 失败分类,输出**和 GitHub 一样的条目形状**;
64
+ - 把 `pollOnce` 里「拿到一页之后的所有事」抽成 `pollWithItems()`:两家共用筛选、推迟、唤醒、水位;
65
+ - `parseRepoSpec()` 认 `gitee:` 前缀、全角冒号、`https://gitee.com/...`、带 `.git` 和尾巴的 URL;
66
+ - 轮询 / 取最后评论 / ack 打标签 / `watch_doctor` 四处都按 provider 分支;
67
+ - 面板「设置 → 凭证」新增 Gitee 令牌输入 + 状态行;仓库输入框提示可填 `gitee:owner/name`。
68
+
69
+ ### 顺带补一个会摘掉插件的坑
70
+ profile 的 `node_modules` 和仓库是**硬链接**:仓库里写坏一个 import,宿主下次加载就整个没有面板/状态栏
71
+ (本轮真的把「鱼」弄丢过一次)。新增 `test/meta.test.mjs` 一条:**必须能 `import('../lib/index.js')`**。
72
+
73
+ ### 证据
74
+ ```
75
+ node --test → 283/283(新增 test/gitee.test.mjs 8 条 + 模块加载守卫 1 条)
76
+ truthy 探针:gitee:a/b / 全角冒号 / gitee.com URL / .git / 带尾巴 URL 全部解析正确
77
+ preflight --fast → 36/36(--no-maintenance 形态)
78
+ ```
79
+
5
80
  ## [0.9.176] - 2026-11-04 —— 凭证页出图核对 + 历史 Release 补了一批
6
81
 
7
82
  ### 真机界面(本轮出图核对)
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  <img src="assets/icon-180.png" width="88" height="88" alt="">
4
4
 
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
6
- [![Version](https://img.shields.io/badge/version-0.9.176-green.svg)](https://github.com/MYCF711/dsh-session-superagent/releases)
6
+ [![Version](https://img.shields.io/badge/version-0.9.178-green.svg)](https://github.com/MYCF711/dsh-session-superagent/releases)
7
7
  [![npm](https://img.shields.io/npm/v/dsh-session-superagent.svg)](https://www.npmjs.com/package/dsh-session-superagent)
8
8
  [![dsh](https://img.shields.io/badge/DeepSeek%20Harness-plugin-orange.svg)](https://github.com/topics/dsh-plugin)
9
9
 
@@ -78,6 +78,27 @@ dsh plugin install /path/to/dsh-session-superagent
78
78
  装进 profile 后是 `file:` 硬链接:改源码即改线上;**但新增文件不会被自动带过去**,
79
79
  加完文件要跑 `pnpm run sync:profile`(否则下次重启插件会整体不挂载,这坑踩过一次)。
80
80
 
81
+ ## 盯 Gitee 仓库(0.9.177 起)
82
+
83
+ 同一个插件既盯 GitHub 也盯 Gitee。写法三种,随便挑一种:
84
+
85
+ ```text
86
+ owner/name # GitHub(默认)
87
+ gitee:owner/name # Gitee
88
+ https://gitee.com/owner/name # 直接粘地址栏(.git 结尾也行)
89
+ ```
90
+
91
+ 区别在这里(用之前该知道):
92
+
93
+ | | GitHub | Gitee |
94
+ |---|---|---|
95
+ | 走什么 | `gh` CLI 或面板 token | REST v5 + 私人令牌 |
96
+ | 条件请求 | 有 ETag,没变化时 304 **不计额度** | **没有** ETag,每轮都真读一次列表 |
97
+ | 批量取评论 | GraphQL 一次查多条 | 逐条 REST(最多前 3 条) |
98
+ | ack 标签 | 不存在会自动建 | 标签必须先存在,否则打不上 |
99
+
100
+ Gitee 私有仓库要在「设置 → 凭证」填私人令牌;公开仓库不填也能读,但打不了 ack 标签。
101
+
81
102
  ## 一次真实运行长什么样
82
103
 
83
104
  1. `watch_start` 登记 watcher(状态存 `~/.dsh/state/session-superagent/watchers.json`);
@@ -123,7 +144,7 @@ dsh plugin install /path/to/dsh-session-superagent
123
144
  ## 开发
124
145
 
125
146
  ```sh
126
- node --test # 274 项单测
147
+ node --test # 285 项单测
127
148
  ```
128
149
 
129
150
  ### 工具输出:文本给人和 agent,JSON 给程序
package/client.js CHANGED
@@ -14,7 +14,7 @@ window.__ModuleLoader__.load({
14
14
  const { useCallback, useEffect, useRef, useState } = React
15
15
 
16
16
  // 客户端版本探针:每次模块加载写一次,用来确认浏览器里跑的是哪一版
17
- const CLIENT_VERSION = '0.9.176'
17
+ const CLIENT_VERSION = '0.9.178'
18
18
  let BASE = '/session-superagent'
19
19
  /**
20
20
  * 挑「最新的那个服务端实例」。
@@ -990,6 +990,8 @@ window.__ModuleLoader__.load({
990
990
  const [stateFilter, setStateFilter] = useState(null)
991
991
  // gh 账号配置目录(只收绝对路径;留空 = 用宿主当前登录的账号)
992
992
  const [ghDir, setGhDir] = useState('')
993
+ // Gitee 私人令牌(和 GitHub token 分开存;留空 = 公开仓库也能读)
994
+ const [giteeToken, setGiteeToken] = useState('')
993
995
  // 建议规则弹层:给"叫醒了没回音"一个下一步动作(只提供可复制的规则,不替客户写仓库文件)
994
996
 
995
997
  // 「我现在手上有没有能渲染的数据」。判断依据必须是**当前 snap**,不是"以前拿到过一次" ——
@@ -1128,11 +1130,13 @@ window.__ModuleLoader__.load({
1128
1130
  const saveCredentials = () => run(async () => {
1129
1131
  const payload = {}
1130
1132
  if (token.trim()) payload.token = token.trim()
1133
+ if (giteeToken.trim()) payload.giteeToken = giteeToken.trim()
1131
1134
  if (ghDir.trim()) payload.ghConfigDir = ghDir.trim()
1132
1135
  else if (ghDir === '') payload.ghConfigDir = '' // 显式清空 = 回到宿主账号
1133
1136
  await call('/credentials', { method: 'POST', body: JSON.stringify(payload) })
1134
1137
  setToken('')
1135
1138
  setGhDir('')
1139
+ setGiteeToken('')
1136
1140
  }, '凭证已保存')
1137
1141
 
1138
1142
  const saveGoal = () => run(async () => {
@@ -1676,7 +1680,7 @@ window.__ModuleLoader__.load({
1676
1680
 
1677
1681
  const trigger = h(Section, { title: '新增主理鱼' },
1678
1682
  h('div', { className: 'dt-form' },
1679
- field('仓库', h(Input, { value: form.repo, placeholder: 'owner/name', onChange: (e) => setForm({ ...form, repo: e.target.value }) })),
1683
+ field('仓库', h(Input, { value: form.repo, placeholder: 'owner/name,或 gitee:owner/name', onChange: (e) => setForm({ ...form, repo: e.target.value }) })),
1680
1684
  field('间隔(秒)', h(Input, { value: form.intervalSec, onChange: (e) => setForm({ ...form, intervalSec: e.target.value }) })),
1681
1685
  field('单次最多唤醒条数', h(Input, { value: form.batchLimit || '', placeholder: '5(1-20)', onChange: (e) => setForm({ ...form, batchLimit: e.target.value }) })),
1682
1686
  field('每小时最多唤醒次数', h(Input, { value: form.maxWakesPerHour || '', placeholder: '6(1-60)', onChange: (e) => setForm({ ...form, maxWakesPerHour: e.target.value }) })),
@@ -1718,8 +1722,10 @@ window.__ModuleLoader__.load({
1718
1722
  ] })),
1719
1723
  h(Section, { key: 'creds', title: '凭证' },
1720
1724
  h(KeyValues, { rows: [['GitHub token', credentials.token === 'none' ? '未配置(回退到已登录的 gh CLI)' : '已配置'], ['SSH 私钥', credentials.sshKeyPath === 'none' ? '未配置(当前版本不使用)' : '已配置'],
1721
- ['gh 账号', credentials.ghConfigDir === 'configured' ? '已绑定独立配置目录(评论挂智能体账号)' : '宿主当前登录的账号']] }),
1725
+ ['gh 账号', credentials.ghConfigDir === 'configured' ? '已绑定独立配置目录(评论挂智能体账号)' : '宿主当前登录的账号'],
1726
+ ['Gitee 令牌', credentials.giteeToken === 'configured' ? '已配置' : '未配置(公开仓库也能读,私有仓库需要)']] }),
1722
1727
  field('Token', h(Input, { type: 'password', value: token, placeholder: 'ghp_… / github_pat_…(留空不改)', onChange: (e) => setToken(e.target.value) })),
1728
+ field('Gitee 令牌', h(Input, { type: 'password', value: giteeToken, placeholder: '私人令牌(留空不改);只盯 GitHub 可以不管' , onChange: (e) => setGiteeToken(e.target.value) })),
1723
1729
  field('gh 账号目录', h(Input, { value: ghDir, placeholder: '绝对路径(留空 = 用宿主账号)', onChange: (e) => setGhDir(e.target.value) })),
1724
1730
  h('div', { className: 'dt-actions' }, h(Btn, { variant: 'primary', onClick: saveCredentials }, '保存凭证')),
1725
1731
  h(Hint, null, '不填也能用:插件直接复用已登录的 gh CLI。填了 gh 账号目录,插件就用那个目录里的账号发言(git push 仍用会话自己的身份,唤醒消息里会提醒会话)。')),
package/lib/gitee.js ADDED
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Gitee(码云)适配层 —— 让「守」不只能盯 GitHub。
3
+ *
4
+ * 为什么要单独一层:`gh` CLI 只服务 GitHub。Gitee 没有等价 CLI,
5
+ * 但它有 REST v5,形状和 GitHub 不完全一样(`state` 有 progressing/rejected、
6
+ * PR 走 `/pulls`、没有 GraphQL、没有 ETag 条件请求)。
7
+ *
8
+ * 设计原则(和 gh-format.js 一致):
9
+ * 1. **纯转换**在这里做完,下游(pollOnce / 筛选 / 唤醒)完全不用知道是哪家;
10
+ * 2. 网络失败只返回结构化错误,不抛 —— 让调用方走统一的失败分类;
11
+ * 3. token 只在这里出现,绝不写日志。
12
+ */
13
+
14
+ export const GITEE_API = 'https://gitee.com/api/v5'
15
+
16
+ /** Gitee 的 state → 我们内部沿用的 GitHub 口径。 */
17
+ export function normalizeGiteeState(raw) {
18
+ const s = String(raw || '').toLowerCase()
19
+ if (s === 'closed' || s === 'rejected') return 'closed'
20
+ return 'open'
21
+ }
22
+
23
+ /**
24
+ * Gitee 条目 → 内部统一形状。
25
+ *
26
+ * 下游只用这些字段:number / title / state / user.login / labels[].name /
27
+ * assignees[].login / html_url / updated_at / state_reason / pull_request / draft。
28
+ */
29
+ export function normalizeGiteeItem(raw, { kind = 'issue' } = {}) {
30
+ const item = raw || {}
31
+ const isPr = kind === 'pull' || Boolean(item.pull_request) || Array.isArray(item.head)
32
+ const state = normalizeGiteeState(item.state)
33
+ const labels = Array.isArray(item.labels)
34
+ ? item.labels.map((l) => (typeof l === 'string' ? { name: l } : { name: l && l.name })).filter((l) => l.name)
35
+ : []
36
+ const out = {
37
+ // Gitee 的 issue 编号是字符串(真机样例:number = "IKSQJH",id = 34933085),
38
+ // PR 才是数字(number = 14)。**别转 Number** —— 转了就全变 0,去重和 ack 全部失效。
39
+ number: item.number === 0 || item.number ? String(item.number) : String(item.id || ''),
40
+ title: String(item.title || ''),
41
+ state,
42
+ // Gitee 用 'rejected' 表示「关闭且不修」;state_reason 只有 reopened 会被下游用来警示
43
+ state_reason: String(item.state_reason || (String(item.state || '').toLowerCase() === 'reopened' ? 'reopened' : '')) || null,
44
+ user: { login: (item.user && item.user.login) || (item.assignee && item.assignee.login) || '?' },
45
+ assignees: item.assignee ? [{ login: item.assignee.login }] : [],
46
+ labels,
47
+ html_url: String(item.html_url || ''),
48
+ created_at: item.created_at || null,
49
+ updated_at: item.updated_at || null,
50
+ }
51
+ if (isPr) {
52
+ out.pull_request = { url: out.html_url }
53
+ out.draft = String(item.state || '').toLowerCase() === 'draft'
54
+ }
55
+ return out
56
+ }
57
+
58
+ export function normalizeGiteeList(issues, pulls) {
59
+ const list = []
60
+ for (const raw of issues || []) list.push(normalizeGiteeItem(raw, { kind: 'issue' }))
61
+ for (const raw of pulls || []) list.push(normalizeGiteeItem(raw, { kind: 'pull' }))
62
+ return list.sort((a, b) => String(b.updated_at || '').localeCompare(String(a.updated_at || '')))
63
+ }
64
+
65
+ /** 统一请求:成功给 {ok:true,data},失败给 {ok:false,status,error},从不抛。 */
66
+ async function request(path, { token, method = 'GET', body = null, fetchImpl = globalThis.fetch, timeoutMs = 20000 } = {}) {
67
+ const url = GITEE_API + path + (token && method === 'GET' ? '' : '')
68
+ const init = {
69
+ method,
70
+ headers: {
71
+ accept: 'application/json',
72
+ ...(token ? { authorization: 'token ' + token } : {}),
73
+ ...(body ? { 'content-type': 'application/json; charset=utf-8' } : {}),
74
+ },
75
+ ...(body ? { body: JSON.stringify(body) } : {}),
76
+ }
77
+ const controller = typeof AbortController === 'function' ? new AbortController() : null
78
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null
79
+ if (controller) init.signal = controller.signal
80
+ try {
81
+ const res = await fetchImpl(url, init)
82
+ const text = await res.text()
83
+ if (!res.ok) {
84
+ // Gitee 的限流是 429;401/403 是 token 问题
85
+ return { ok: false, status: res.status, error: String(text || '').slice(0, 240) }
86
+ }
87
+ let data = null
88
+ try { data = text ? JSON.parse(text) : null } catch { return { ok: false, status: res.status, error: 'non-json body' } }
89
+ return { ok: true, status: res.status, data }
90
+ } catch (error) {
91
+ return { ok: false, status: 0, error: String((error && error.message) || error).slice(0, 200) }
92
+ } finally {
93
+ if (timer) clearTimeout(timer)
94
+ }
95
+ }
96
+
97
+ /** 拉一页 issue + PR(Gitee 两者分属不同端点,缺 token 时公开仓库也能读)。 */
98
+ export async function listGiteeItems({ repo, token = '', perPage = 20, fetchImpl } = {}) {
99
+ const q = 'state=all&sort=updated&direction=desc&per_page=' + Math.max(1, Math.min(100, Number(perPage) || 20))
100
+ const [issues, pulls] = await Promise.all([
101
+ request(`/repos/${repo}/issues?${q}`, { token, fetchImpl }),
102
+ request(`/repos/${repo}/pulls?${q}`, { token, fetchImpl }),
103
+ ])
104
+ if (!issues.ok && !pulls.ok) {
105
+ return { ok: false, status: issues.status || pulls.status, error: issues.error || pulls.error }
106
+ }
107
+ return {
108
+ ok: true,
109
+ items: normalizeGiteeList(issues.ok ? issues.data : [], pulls.ok ? pulls.data : []),
110
+ // 一半成功也要说清楚:否则客户以为 PR 一条都没有
111
+ partial: !issues.ok || !pulls.ok ? (issues.ok ? 'pulls' : 'issues') : null,
112
+ }
113
+ }
114
+
115
+ /** 某条 issue/PR 的最后一条评论(谁、什么时候)——唤醒消息用它回答「现在是有人在等吗」。 */
116
+ export async function fetchGiteeLastComment({ repo, token = '', item, selfLogin = '', fetchImpl } = {}) {
117
+ // 编号可能是字符串(issue 形如 IKSQJH)也可能是数字(PR 形如 14):都按原样拼进 URL
118
+ const number = item && item.number != null ? String(item.number) : ''
119
+ if (!number) return null
120
+ const kind = item && item.pull_request ? 'pulls' : 'issues'
121
+ const res = await request(`/repos/${repo}/${kind}/${number}/comments?per_page=1&sort=created&direction=desc`, { token, fetchImpl })
122
+ if (!res.ok || !Array.isArray(res.data) || res.data.length === 0) return null
123
+ const last = res.data[res.data.length - 1]
124
+ const login = (last.user && last.user.login) || ''
125
+ return {
126
+ login,
127
+ at: last.created_at || null,
128
+ // 自己留的评论不算「有人在等」——和 GitHub 那条 GraphQL 分支保持同一口径
129
+ self: Boolean(selfLogin) && login === selfLogin,
130
+ }
131
+ }
132
+
133
+ /** 打标签(ack 用)。Gitee 对 issue 有这个端点;PR 视同 issue。 */
134
+ export async function addGiteeLabel({ repo, token = '', number, label, fetchImpl } = {}) {
135
+ return request(`/repos/${repo}/issues/${number}/labels`, { token, method: 'POST', body: { labels: [label] }, fetchImpl })
136
+ }
137
+
138
+ /** 当前 token 是谁(doctor 用)。 */
139
+ export async function giteeWhoami({ token = '', fetchImpl } = {}) {
140
+ return request('/user', { token, fetchImpl })
141
+ }
142
+
143
+ /** 仓库是否可读(doctor 用)。 */
144
+ export async function giteeRepo({ repo, token = '', fetchImpl } = {}) {
145
+ return request(`/repos/${repo}`, { token, fetchImpl })
146
+ }
package/lib/index.js CHANGED
@@ -23,8 +23,10 @@ import { zstdDecompressSync } from 'node:zlib'
23
23
 
24
24
  import { redact } from './redact.js'
25
25
  import { decodeBody } from './body.js'
26
+ import { listGiteeItems, fetchGiteeLastComment, addGiteeLabel, giteeWhoami, giteeRepo } from './gitee.js'
26
27
  import {
27
28
  advanceSeen, applyWatcherAction, batchFresh, decideWake, DEFAULT_ACK_LABEL, formatWatchText,
29
+ parseRepoSpec,
28
30
  TRIAGE_SIGNALS, accessNote, wakeCriteria, sessionMissingVerdict, buildCommentBatchQuery, classifyGhError, commentSummaryLine, parseCommentBatch, pickSuggestion, repoStructureNote, countReasons, filterReason, formatGhCall, diagnoseEmptyBody, diagnoseBadBody, isAuthBroken, hasAckLabel, jitterMs, parseGhInclude, retryAfterMs, throttleDelayMs, inActiveHours, newestUpdatedAt, nextDelayMs, enterActiveHoursDefer, recordOtherError, permanentBackoffMs, RETRY_BUDGET_ATTEMPTS, RETRY_SLOW_CAP_MINUTES, pushAbsorbed, pushFiltered, normalizeFilters, partitionItems, passesFilters,
29
31
  shouldRunCleanup,
30
32
  bumpDailyWakes,
@@ -40,7 +42,7 @@ import {
40
42
 
41
43
  export const name = 'dsh-session-superagent'
42
44
  /** 服务端版本:随 package.json 同步(meta 测试守着)。客户端据此挑「最新的那个实例」。 */
43
- export const SERVER_VERSION = '0.9.176'
45
+ export const SERVER_VERSION = '0.9.178'
44
46
  export const inject = ['tools', 'agents', 'webServer']
45
47
  /** 一条会话每小时最多被唤醒几次(跨所有守累计)。单守上限挡不住多守叠加。 */
46
48
  // 本进程启动时刻:用来区分「刚重启还没轮到」与「定时器真的丢了」
@@ -224,7 +226,8 @@ function secretsSummary() {
224
226
  // 从不在面板回显路径(Windows 路径里的反斜杠曾让掩码整段漏出)
225
227
  sshKeyHint: null,
226
228
  // 「用哪个 gh 账号」同理:只回配没配,不回路径(取自 PR #7 的设计)
227
- ghConfigDir: s.ghConfigDir ? 'configured' : 'none',
229
+ ghConfigDir: s.ghConfigDir ? 'configured' : 'none',
230
+ giteeToken: s.giteeToken ? 'configured' : 'none',
228
231
  ghConfigDirHint: null,
229
232
  updatedAt: s.updatedAt ?? null,
230
233
  }
@@ -877,7 +880,19 @@ async function viewerLogin() {
877
880
  return viewerCache.login
878
881
  }
879
882
 
880
- async function fetchLastComments(repo, items, maxItems = 3) {
883
+ async function fetchLastComments(repo, items, maxItems = 3, options = {}) {
884
+ // Gitee:没有 GraphQL 批量,逐条 REST。条数本来就只取前 3 条,代价可接受。
885
+ // Gitee 的条目不一定带 comments 计数,所以这里不按计数过滤,直接取前几条。
886
+ if (options.provider === 'gitee') {
887
+ const picks = (items || []).slice(0, maxItems)
888
+ await Promise.all(picks.map(async (item) => {
889
+ try {
890
+ const info = await fetchGiteeLastComment({ repo, token: String(options.token || ''), item })
891
+ if (info && info.login) item.lastComment = info
892
+ } catch { /* 少一行信息,不阻断唤醒 */ }
893
+ }))
894
+ return
895
+ }
881
896
  const targets = (items || []).filter((item) => Number(item.comments) > 0).slice(0, maxItems)
882
897
  if (targets.length === 0) return
883
898
  const me = await viewerLogin()
@@ -931,6 +946,50 @@ async function pollOnce(ctx, entry, baseMs) {
931
946
  return
932
947
  }
933
948
  // 条件请求:带上上次的 ETag,没变化时 GitHub 回 304,且**不计入**速率限制
949
+ // ── Gitee 分支 ────────────────────────────────────────────────────────────
950
+ // Gitee 没有 gh CLI、没有 GraphQL、没有 ETag 条件请求;用 REST v5 拉一页,
951
+ // 在 lib/gitee.js 里归一成和 GitHub 一样的条目形状,下面所有筛选/唤醒逻辑共用。
952
+ if (entry.provider === 'gitee') {
953
+ const listed = await listGiteeItems({ repo: entry.repo, token: String(readSecrets().giteeToken || ''), perPage: 20 })
954
+ entry.lastPoll = new Date().toISOString()
955
+ if (!listed.ok) {
956
+ const status = Number(listed.status) || 0
957
+ // 401/403 = token 问题(不会自己好);429 = 限流(会);其它按网络抖动处理
958
+ const kind = status === 401 || status === 403 ? 'auth' : status === 429 ? 'ratelimit' : status === 404 ? 'notfound' : 'network'
959
+ const hint = kind === 'auth' ? '(Gitee token 无效或没权限:在设置里填 Gitee 私人令牌)'
960
+ : kind === 'ratelimit' ? '(被 Gitee 限流:下一轮再试)'
961
+ : kind === 'notfound' ? '(Gitee 仓库不存在,或 token 看不到这个私有仓库)'
962
+ : '(连不上 Gitee:' + String(listed.error || '').slice(0, 80) + ')'
963
+ if (kind === 'ratelimit') {
964
+ entry.nextAt = new Date(Date.now() + 60 * 1000).toISOString()
965
+ entry.lastDeferred = '被 Gitee 限流,等 60 秒'
966
+ entry.deferReason = 'ratelimit'
967
+ entry.lastError = null
968
+ noteEvent(entry, 'ratelimit', entry.lastDeferred)
969
+ return
970
+ }
971
+ setEntryError(entry, ('Gitee ' + (status || '请求失败') + hint).slice(0, 300))
972
+ if (kind === 'auth') entry.needsReauth = true
973
+ bumpFailure(entry, baseMs)
974
+ return
975
+ }
976
+ // 一半成功(issue 拿到、PR 没拿到)要说出来,否则客户以为 PR 一条都没有
977
+ if (listed.partial) noteEvent(entry, 'partial', 'Gitee ' + (listed.partial === 'pulls' ? 'PR' : 'issue') + ' 列表这一轮没拿到')
978
+ const items = listed.items || []
979
+ if (items.length === 0) {
980
+ entry.lastError = null
981
+ entry.needsReauth = false
982
+ entry.consecutiveFailures = 0
983
+ entry.nextAt = null
984
+ entry.lastDeferred = UNCHANGED_TEXT
985
+ entry.deferReason = 'unchanged'
986
+ noteEvent(entry, 'unchanged', entry.lastDeferred)
987
+ return
988
+ }
989
+ // 归一后的条目直接交给共用判定:形状已和 GitHub 一致,后面不该再分两家
990
+ return pollWithItems(ctx, entry, baseMs, { status: 200, etag: null, body: JSON.stringify(items) })
991
+ }
992
+
934
993
  const args = ['api', '--include', `repos/${entry.repo}/issues?state=all&sort=updated&direction=desc&per_page=20`]
935
994
  if (entry.etag) args.push('-H', 'If-None-Match: ' + entry.etag)
936
995
  const res = await run('gh', args, { timeoutMs: 45000, env: ghEnv() })
@@ -1019,6 +1078,16 @@ async function pollOnce(ctx, entry, baseMs) {
1019
1078
  // 原因:下面有多个提前 return 的分支(会话正忙 / 会话上限 / 每小时上限 / 本轮被暂停 / 会话已不在)。
1020
1079
  // 它们刻意不动 seen/cursor(注释也写了「否则攒着等于丢掉」),但 ETag 若已前移,
1021
1080
  // 下一轮条件请求就会拿到 304 并在上面直接 return,fresh 永远不再重算 —— 效果同样是「攒着=丢掉」。
1081
+ return pollWithItems(ctx, entry, baseMs, parsed)
1082
+ }
1083
+
1084
+ /**
1085
+ * 拿到一页条目之后的所有事:解析 / 过滤 / 推迟 / 唤醒 / 记账。
1086
+ *
1087
+ * 抽出来是为了让 GitHub 与 Gitee 共用同一套判定 —— 两家只有「怎么拿数据」不同,
1088
+ * 「要不要叫醒、叫醒说什么、水位怎么走」必须完全一致,否则同一条 bug 要修两遍。
1089
+ */
1090
+ async function pollWithItems(ctx, entry, baseMs, parsed) {
1022
1091
  const pendingEtag = parsed.etag
1023
1092
  const commitEtag = () => { if (pendingEtag) entry.etag = pendingEtag }
1024
1093
  let items
@@ -1181,7 +1250,10 @@ async function pollOnce(ctx, entry, baseMs) {
1181
1250
  const isolation = await prepareIsolation(entry)
1182
1251
  if (isolation && isolation.dir) entry.lastWorktree = isolation.dir
1183
1252
  // 批次前几条补「最后是谁在说话」(最多 3 条,失败静默)
1184
- await fetchLastComments(entry.repo, listed)
1253
+ await fetchLastComments(entry.repo, listed, 3, {
1254
+ provider: entry.provider,
1255
+ token: entry.provider === 'gitee' ? String(readSecrets().giteeToken || '') : '',
1256
+ })
1185
1257
  // 首次同步:这条守刚建好,或者宿主换了机器(cursor 还是 null)。
1186
1258
  // 此时"有动态"其实是"仓库里本来就有这些待处理",说成新动态会让人以为刚刚发生。
1187
1259
  const firstSync = !entry.cursor
@@ -1606,8 +1678,12 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
1606
1678
  if (result.enabled === true) startWatcher(state.watchers[id])
1607
1679
  return json(res, 200, result)
1608
1680
  }
1609
- const repo = String(body.repo || '').trim()
1610
- if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) return json(res, 400, { error: 'repo must be owner/name' })
1681
+ // 认三种写法:`owner/name` / `gitee:owner/name` / `https://gitee.com/owner/name`。
1682
+ // 客户是从浏览器地址栏复制的,让他手动删前缀是没必要的摩擦。
1683
+ const spec = parseRepoSpec(body.repo)
1684
+ if (!spec.ok) return json(res, 400, { error: spec.error })
1685
+ const repo = spec.repo
1686
+ const provider = spec.provider
1611
1687
  const sessionId = String(body.sessionId || '').trim()
1612
1688
  if (!sessionId) return json(res, 400, { error: 'sessionId is required (open the panel in the session that should be woken)' })
1613
1689
  // 若这个实例的 ctx 已经 dispose(宿主重载后旧 handler 仍在服务请求),
@@ -1622,15 +1698,17 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
1622
1698
  const intervalSec = Math.max(30, Math.min(3600, Number(body.intervalSec) || 60))
1623
1699
  const state = readState()
1624
1700
  state.watchers = state.watchers || {}
1625
- const id = repo + '#' + sessionId
1701
+ // id 里带 provider:同一个 owner/name 在两家可能都存在,混在一起会互相覆盖
1702
+ const id = (provider === 'gitee' ? 'gitee:' : '') + repo + '#' + sessionId
1626
1703
  const created = !(state.watchers && state.watchers[id])
1627
1704
  const entry = state.watchers[id] || {
1628
- id, repo, sessionId, cursor: null, seen: {}, lastReported: {},
1705
+ id, repo, provider, sessionId, cursor: null, seen: {}, lastReported: {},
1629
1706
  cooldownMs: 180000, createdAt: new Date().toISOString(),
1630
1707
  filters: normalizeFilters(), batchLimit: 5, maxWakesPerHour: 6,
1631
1708
  wakeTimes: [], consecutiveFailures: 0, ackLabel: DEFAULT_ACK_LABEL,
1632
1709
  isolated: false, workdir: null,
1633
1710
  }
1711
+ entry.provider = provider
1634
1712
  entry.intervalSec = intervalSec
1635
1713
  // 只有真正带了 goal 才覆盖:GUI 编辑保存不带这个字段,覆盖会清空
1636
1714
  if (typeof body.goal === 'string') entry.goal = body.goal.slice(0, 500)
@@ -1722,6 +1800,12 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
1722
1800
  }
1723
1801
  // 「用哪个 gh 账号」:指向只登录了智能体账号的配置目录;空串 = 回到宿主当前账号。
1724
1802
  // 只收绝对路径:相对路径会随 cwd 漂移,把设置指向一个不存在的地方。
1803
+ // Gitee 私人令牌:和 GitHub token 分开存(两家互不通用)
1804
+ if (typeof body.giteeToken === 'string') {
1805
+ const gt = body.giteeToken.trim()
1806
+ if (gt === '') delete next.giteeToken
1807
+ else next.giteeToken = gt
1808
+ }
1725
1809
  if (typeof body.ghConfigDir === 'string') {
1726
1810
  const dir = body.ghConfigDir.trim()
1727
1811
  if (dir === '') delete next.ghConfigDir
@@ -1938,10 +2022,12 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
1938
2022
  format: { type: 'string', description: "'text' (default) or 'json'." },
1939
2023
  },
1940
2024
  async execute(args) {
2025
+ // 编号允许两种:GitHub 是数字(14),Gitee 的 issue 是字符串(IKSQJH)。
2026
+ // 以前一律 Number(),Gitee 那边会被过滤成空数组,报「number is required」—— 看着像用户没填。
1941
2027
  const numbers = String(args.numbers || args.number || '')
1942
2028
  .split(',')
1943
- .map((v) => Number(v.trim()))
1944
- .filter((v) => Number.isFinite(v) && v > 0)
2029
+ .map((v) => v.trim())
2030
+ .filter((v) => /^[A-Za-z0-9_-]+$/.test(v))
1945
2031
  if (numbers.length === 0) return '[error: number (or numbers) is required]'
1946
2032
  const state = readState()
1947
2033
  const watchers = Object.values(state.watchers || {})
@@ -1951,11 +2037,20 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
1951
2037
  if (!entry) return '[error: no watcher for that repo — start one with watch_start first]'
1952
2038
  const label = String(args.label || entry.ackLabel || DEFAULT_ACK_LABEL)
1953
2039
  // GitHub 不会因为加标签而自动建标签:不存在时返回 422。先幂等建一次(已存在也返回 422,忽略)。
1954
- await run('gh', ['api', '-X', 'POST', `repos/${entry.repo}/labels`, '-f', `name=${label}`, '-f', 'color=ededed'], { env: ghEnv() })
2040
+ // Gitee 没有「建标签」的独立端点(标签必须先存在),所以这边只打标签;
2041
+ // 标签不存在时它会 404 —— 让调用方看到真实原因,别假装成功。
2042
+ if (entry.provider !== 'gitee') {
2043
+ await run('gh', ['api', '-X', 'POST', `repos/${entry.repo}/labels`, '-f', `name=${label}`, '-f', 'color=ededed'], { env: ghEnv() })
2044
+ }
1955
2045
  const results = []
1956
2046
  let failed = null
1957
2047
  for (const number of numbers) {
1958
- const res = await run('gh', ['api', '-X', 'POST', `repos/${entry.repo}/issues/${number}/labels`, '-f', `labels[]=${label}`], { env: ghEnv() })
2048
+ const res = entry.provider === 'gitee'
2049
+ ? await (async () => {
2050
+ const r = await addGiteeLabel({ repo: entry.repo, token: String(readSecrets().giteeToken || ''), number, label })
2051
+ return { code: r.ok ? 0 : 1, stdout: '', stderr: r.ok ? '' : String(r.status || '') + ' ' + String(r.error || '') }
2052
+ })()
2053
+ : await run('gh', ['api', '-X', 'POST', `repos/${entry.repo}/issues/${number}/labels`, '-f', `labels[]=${label}`], { env: ghEnv() })
1959
2054
  if (res.code !== 0) {
1960
2055
  failed = { number, text: redact([res.stdout, res.stderr].filter(Boolean).join(' ').trim()).slice(0, 200) }
1961
2056
  break
@@ -2129,7 +2224,23 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2129
2224
  }
2130
2225
 
2131
2226
  for (const entry of wanted) {
2132
- // 2. 仓库可访问
2227
+ // 2. 仓库可访问(Gitee 走 REST,不走 gh)
2228
+ if (entry.provider === 'gitee') {
2229
+ const token = String(readSecrets().giteeToken || '')
2230
+ const repoRes = await giteeRepo({ repo: entry.repo, token })
2231
+ if (repoRes.ok) {
2232
+ lines.push('OK gitee:' + entry.repo + ' 可访问')
2233
+ } else {
2234
+ const status = Number(repoRes.status) || 0
2235
+ const why = status === 401 || status === 403 ? 'Gitee token 无效或没权限(在设置里填私人令牌)'
2236
+ : status === 404 ? 'Gitee 仓库不存在,或 token 看不到这个私有仓库'
2237
+ : '连不上 Gitee(' + String(repoRes.error || '').slice(0, 80) + ')'
2238
+ lines.push('FAIL gitee:' + entry.repo + ' 不可访问:' + why)
2239
+ }
2240
+ if (!token) lines.push('WARN 没有配置 Gitee token:公开仓库能读,私有仓库读不到,也打不了 ack 标签')
2241
+ lines.push('INFO Gitee 没有 ETag 条件请求,所以这条守每轮都会真的读一次列表(注意额度)')
2242
+ continue
2243
+ }
2133
2244
  const repoRes = await run('gh', ['api', `repos/${entry.repo}`, '--jq', '.full_name'], { env: ghEnv() })
2134
2245
  if (repoRes.code === 0) {
2135
2246
  lines.push(`OK ${entry.repo} 可访问:${repoRes.stdout.trim()}`)
package/lib/watch.js CHANGED
@@ -1056,3 +1056,42 @@ export function sessionMissingVerdict({ missingSince, now = Date.now(), graceMs
1056
1056
  if (left > 0) return { grace: true, startedAt: new Date(since).toISOString(), waitMin: Math.max(1, Math.ceil(left / 60000)) }
1057
1057
  return { grace: false, waitedMin: Math.max(1, Math.round((now - since) / 60000)) }
1058
1058
  }
1059
+
1060
+ /**
1061
+ * 解析仓库写法:`owner/name`、`github:owner/name`、`gitee:owner/name`,
1062
+ * 以及 `https://github.com/owner/name`、`https://gitee.com/owner/name`(可带 .git / 结尾斜杠)。
1063
+ *
1064
+ * 为什么要认 URL:客户是从浏览器地址栏复制的,让他手动删 `https://gitee.com/` 是没必要的摩擦。
1065
+ * 认不出来就返回 ok:false + 具体原因,别在轮询阶段才 404。
1066
+ */
1067
+ export function parseRepoSpec(input) {
1068
+ const raw = String(input || '').trim()
1069
+ if (!raw) return { ok: false, error: 'repo 不能为空' }
1070
+ let provider = 'github'
1071
+ let rest = raw
1072
+
1073
+ const url = raw.match(/^https?:\/\/([^/]+)\/(.+)$/i)
1074
+ if (url) {
1075
+ const host = url[1].toLowerCase()
1076
+ rest = url[2]
1077
+ if (host === 'gitee.com' || host.endsWith('.gitee.com')) provider = 'gitee'
1078
+ else if (host === 'github.com' || host.endsWith('.github.com')) provider = 'github'
1079
+ else return { ok: false, error: '只支持 github.com 与 gitee.com 的地址' }
1080
+ } else {
1081
+ const prefixed = raw.match(/^(github|gitee)\s*[::]\s*(.+)$/i)
1082
+ if (prefixed) {
1083
+ provider = prefixed[1].toLowerCase()
1084
+ rest = prefixed[2]
1085
+ }
1086
+ }
1087
+
1088
+ rest = rest.replace(/\.git$/i, '').replace(/\/+$/, '')
1089
+ // URL 里可能还带着 /issues 之类的尾巴:只取前两段
1090
+ const parts = rest.split('/').filter(Boolean)
1091
+ if (parts.length < 2) return { ok: false, error: '要写成 owner/name' }
1092
+ const [owner, name] = parts
1093
+ if (!/^[A-Za-z0-9_.-]+$/.test(owner) || !/^[A-Za-z0-9_.-]+$/.test(name)) {
1094
+ return { ok: false, error: 'owner/name 只能包含字母、数字、下划线、点、短横线' }
1095
+ }
1096
+ return { ok: true, provider, repo: owner + '/' + name, spec: provider === 'github' ? owner + '/' + name : 'gitee:' + owner + '/' + name }
1097
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-session-superagent",
3
- "version": "0.9.176",
3
+ "version": "0.9.178",
4
4
  "description": "Session-level superagent for DeepSeek Harness: watch a GitHub repository and wake a session when something needs doing. Credentials never reach the model.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",