dsh-session-superagent 0.10.11 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,63 @@
1
+
2
+ export function normalizeSelf(login) {
3
+ return String(login ?? '').trim().replace(/^@+/, '').toLowerCase()
4
+ }
5
+
6
+ function normalizeRepo(name) {
7
+ return String(name ?? '').trim().toLowerCase()
8
+ }
9
+
10
+ export function isForkPr(pr) {
11
+ if (!pr || typeof pr !== 'object') return false
12
+ const head = normalizeRepo(pr.headRepo)
13
+ const base = normalizeRepo(pr.baseRepo)
14
+ return Boolean(head && base && head !== base)
15
+ }
16
+
17
+ export function pickNewComments(comments, seenId) {
18
+ const list = Array.isArray(comments) ? comments : []
19
+ const threshold = Number(seenId) || 0
20
+ return list.filter((comment) => {
21
+ const id = Number(comment && comment.id)
22
+ return Number.isFinite(id) && id > threshold
23
+ })
24
+ }
25
+
26
+ export function shouldWake(comments, self) {
27
+ const list = Array.isArray(comments) ? comments : []
28
+ const me = normalizeSelf(self)
29
+ return list.some((comment) => normalizeSelf(comment && comment.author) !== me)
30
+ }
31
+
32
+ export function buildPrWakeText(opts) {
33
+ const options = opts && typeof opts === 'object' ? opts : {}
34
+ const comments = Array.isArray(options.comments) ? options.comments : []
35
+ const base = String(options.base ?? '')
36
+ const number = String(options.number ?? '')
37
+ const lines = [
38
+ '【PR 响应】' + base + '#' + number + ' 有 ' + comments.length + ' 条新评论',
39
+ '',
40
+ 'PR: ' + String(options.title ?? ''),
41
+ '分支: ' + String(options.branch ?? ''),
42
+ ]
43
+ for (const comment of comments) {
44
+ const item = comment && typeof comment === 'object' ? comment : {}
45
+ const body = String(item.body ?? '').trim()
46
+ lines.push('评论者: ' + String(item.author ?? '') + '(非本人)')
47
+ lines.push('时间: ' + String(item.createdAt ?? ''))
48
+ lines.push('')
49
+ const bodyLines = body.length > 0 ? body.split(/\r\n|\n|\r/) : ['']
50
+ for (const line of bodyLines) lines.push('> ' + line)
51
+ lines.push('')
52
+ }
53
+ const auditMode = String(options.auditMode === 'inline' ? 'inline' : 'subagent')
54
+ const audits = []
55
+ if (options.audit === true) audits.push('审计')
56
+ if (options.adversarialAudit === true) audits.push('对抗性审计')
57
+ const review = audits.length > 0
58
+ ? '自审(' + auditMode + ' 驱动的' + audits.join('和') + ')'
59
+ : '自审'
60
+ lines.push('处理建议: 阅读评论 → 从 remote 同步代码 → 修改代码 → ' + review + ' → 提交 → 回评')
61
+ if (options.goal) lines.push('目标: ' + String(options.goal))
62
+ return lines.join('\n')
63
+ }
@@ -0,0 +1,189 @@
1
+ /**
2
+ * 两层 Admission Eval 房。
3
+ *
4
+ * gate 是唯一授权入口:只有明确的 accept 才会调用 assessment;reject、
5
+ * unknown、非法返回和异常都不会 fail-open。assessment 只决定接受、拒绝或
6
+ * 未知,永远没有机会推翻已经完成的确定性拒绝。
7
+ *
8
+ * 端口:
9
+ * - gate(candidate):同步或异步返回 Decision;
10
+ * - assessment(candidate, { signal, gate }):异步模型评估,可使用 signal 取消。
11
+ *
12
+ * Decision 可以是 accept/reject/unknown 字符串、{ disposition, reason }、
13
+ * 布尔值或 { allowed, reason };null/undefined 表示 unknown。所有返回均为
14
+ * 新的完整结果:{ stage, disposition, reason, gate, assessment, error }。
15
+ */
16
+
17
+ const DISPOSITIONS = new Set(['accept', 'reject', 'unknown'])
18
+ const DEFAULT_TIMEOUT_MS = 30_000
19
+
20
+ function isObject(value) {
21
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
22
+ }
23
+
24
+ function invalidResult(stage) {
25
+ const error = new TypeError(`${stage} must return accept, reject, unknown, or an allowed/disposition result`)
26
+ error.name = 'AdmissionResultError'
27
+ error.code = stage === 'gate' ? 'GATE_INVALID_RESULT' : 'ASSESSMENT_INVALID_RESULT'
28
+ return error
29
+ }
30
+
31
+ function normalizeDecision(value, stage) {
32
+ let disposition
33
+
34
+ if (value === null || value === undefined) {
35
+ disposition = 'unknown'
36
+ } else if (typeof value === 'boolean') {
37
+ disposition = value ? 'accept' : 'reject'
38
+ } else if (typeof value === 'string' && DISPOSITIONS.has(value)) {
39
+ disposition = value
40
+ } else if (isObject(value)) {
41
+ if (value.disposition !== undefined) {
42
+ if (!DISPOSITIONS.has(value.disposition)) throw invalidResult(stage)
43
+ disposition = value.disposition
44
+ } else {
45
+ const hasAllowed = Object.hasOwn(value, 'allowed')
46
+ const hasAllow = Object.hasOwn(value, 'allow')
47
+ if (!hasAllowed && !hasAllow) throw invalidResult(stage)
48
+ const allowed = hasAllowed ? value.allowed : value.allow
49
+ if (allowed === null || allowed === undefined) disposition = 'unknown'
50
+ else if (typeof allowed === 'boolean') disposition = allowed ? 'accept' : 'reject'
51
+ else throw invalidResult(stage)
52
+ }
53
+ } else {
54
+ throw invalidResult(stage)
55
+ }
56
+
57
+ const suppliedReason = isObject(value) && typeof value.reason === 'string'
58
+ ? value.reason.trim()
59
+ : ''
60
+ return {
61
+ disposition,
62
+ reason: suppliedReason || `${stage}-${disposition}`,
63
+ }
64
+ }
65
+
66
+ function errorResult(error, fallbackCode) {
67
+ return {
68
+ name: String(error && error.name || 'Error'),
69
+ message: String(error && error.message || error || 'unknown error'),
70
+ code: String(error && error.code || fallbackCode),
71
+ }
72
+ }
73
+
74
+ function unknownDecision(stage, reason) {
75
+ return { disposition: 'unknown', reason }
76
+ }
77
+
78
+ function completeResult(stage, gate, assessment, error = null) {
79
+ const terminal = stage === 'gate' ? gate : assessment
80
+ return {
81
+ stage,
82
+ disposition: terminal.disposition,
83
+ reason: terminal.reason,
84
+ gate: { ...gate },
85
+ assessment: assessment ? { ...assessment } : null,
86
+ error,
87
+ }
88
+ }
89
+
90
+ function failedResult(stage, reason, gate, assessment, error, fallbackCode) {
91
+ const failed = unknownDecision(stage, reason)
92
+ return completeResult(
93
+ stage,
94
+ stage === 'gate' ? failed : gate,
95
+ stage === 'assessment' ? failed : assessment,
96
+ errorResult(error, fallbackCode),
97
+ )
98
+ }
99
+
100
+ function timeoutError(timeoutMs) {
101
+ const error = new Error(`assessment timed out after ${timeoutMs} ms`)
102
+ error.name = 'TimeoutError'
103
+ error.code = 'ASSESSMENT_TIMEOUT'
104
+ return error
105
+ }
106
+
107
+ /**
108
+ * 执行一次两层准入评估。timeoutMs=0 表示不为 assessment 设置房间级超时;
109
+ * 默认 30 秒。调用方注入的 timers 只用于超时,不产生额外后台任务。
110
+ */
111
+ export async function evaluateAdmission({
112
+ candidate = null,
113
+ gate,
114
+ assessment,
115
+ timeoutMs = DEFAULT_TIMEOUT_MS,
116
+ timers = globalThis,
117
+ } = {}) {
118
+ if (typeof gate !== 'function') throw new TypeError('evaluateAdmission requires gate')
119
+ const budget = Number(timeoutMs)
120
+ if (!Number.isFinite(budget) || budget < 0) {
121
+ throw new TypeError('evaluateAdmission timeoutMs must be a non-negative finite number')
122
+ }
123
+
124
+ let gateDecision
125
+ try {
126
+ gateDecision = normalizeDecision(await gate(candidate), 'gate')
127
+ } catch (error) {
128
+ const invalid = error && error.name === 'AdmissionResultError'
129
+ return failedResult(
130
+ 'gate',
131
+ invalid ? 'gate-invalid' : 'gate-error',
132
+ null,
133
+ null,
134
+ error,
135
+ 'GATE_ERROR',
136
+ )
137
+ }
138
+
139
+ // 这里同时挡住 reject 与 unknown:assessment 不能成为第二授权入口。
140
+ if (gateDecision.disposition !== 'accept') {
141
+ return completeResult('gate', gateDecision, null)
142
+ }
143
+
144
+ if (typeof assessment !== 'function') {
145
+ return failedResult(
146
+ 'assessment',
147
+ 'assessment-error',
148
+ gateDecision,
149
+ null,
150
+ new TypeError('evaluateAdmission requires assessment after gate accept'),
151
+ 'ASSESSMENT_ERROR',
152
+ )
153
+ }
154
+
155
+ const controller = new AbortController()
156
+ let timer = null
157
+ try {
158
+ const pending = Promise.resolve().then(() => assessment(candidate, {
159
+ signal: controller.signal,
160
+ gate: { ...gateDecision },
161
+ }))
162
+
163
+ let rawAssessment
164
+ if (budget === 0) {
165
+ rawAssessment = await pending
166
+ } else {
167
+ const expired = new Promise((resolve, reject) => {
168
+ timer = timers.setTimeout(() => {
169
+ const error = timeoutError(budget)
170
+ controller.abort(error)
171
+ reject(error)
172
+ }, budget)
173
+ })
174
+ rawAssessment = await Promise.race([pending, expired])
175
+ }
176
+
177
+ const assessmentDecision = normalizeDecision(rawAssessment, 'assessment')
178
+ return completeResult('assessment', gateDecision, assessmentDecision)
179
+ } catch (error) {
180
+ const reason = error && error.code === 'ASSESSMENT_TIMEOUT'
181
+ ? 'assessment-timeout'
182
+ : error && error.name === 'AdmissionResultError'
183
+ ? 'assessment-invalid'
184
+ : 'assessment-error'
185
+ return failedResult('assessment', reason, gateDecision, null, error, 'ASSESSMENT_ERROR')
186
+ } finally {
187
+ if (timer !== null) timers.clearTimeout(timer)
188
+ }
189
+ }
@@ -0,0 +1,221 @@
1
+ /**
2
+ * 水位 v2 · 数据源房。
3
+ *
4
+ * 必需针脚:list / keyOf / cursorOf / compareCursor。
5
+ * 可选针脚:listComments(comments)、acknowledge(ack)。
6
+ * 网络实现可注入,状态与决策房不需要知道 GitHub/Gitee 的字段。
7
+ */
8
+ // KB: tool-panel-parity.md —— provider 能力声明与可选针脚必须一致。
9
+ import { createHash } from 'node:crypto'
10
+ import { parseGhInclude } from '../gh-format.js'
11
+ import { redact } from '../redact.js'
12
+ import {
13
+ listGiteeItems,
14
+ getGiteeItem,
15
+ fetchGiteeLastComment,
16
+ ensureGiteeLabel,
17
+ addGiteeLabel,
18
+ addGiteeComment,
19
+ } from '../gitee.js'
20
+
21
+ const CAPABILITY_METHOD = { comments: 'listComments', ack: 'acknowledge' }
22
+
23
+ export class CapabilityError extends Error {
24
+ constructor(provider, capability) {
25
+ super(`provider ${provider} does not support capability: ${capability}`)
26
+ this.name = 'CapabilityError'
27
+ this.code = 'CAPABILITY_MISSING'
28
+ this.provider = provider
29
+ this.capability = capability
30
+ }
31
+ }
32
+
33
+ export function defineProvider(spec = {}) {
34
+ const name = String(spec.name || 'anonymous')
35
+ for (const method of ['list', 'keyOf', 'cursorOf', 'compareCursor']) {
36
+ if (typeof spec[method] !== 'function') throw new TypeError(`provider ${name} missing required pin: ${method}`)
37
+ }
38
+ const capabilities = new Set(['issues', ...(Array.isArray(spec.capabilities) ? spec.capabilities : [])])
39
+ if (typeof spec.listComments === 'function') capabilities.add('comments')
40
+ if (typeof spec.acknowledge === 'function') capabilities.add('ack')
41
+ for (const [capability, method] of Object.entries(CAPABILITY_METHOD)) {
42
+ if (capabilities.has(capability) && typeof spec[method] !== 'function') {
43
+ throw new TypeError(`provider ${name} declares ${capability} but missing pin: ${method}`)
44
+ }
45
+ }
46
+ const frozen = Object.freeze([...capabilities])
47
+ return Object.freeze({
48
+ name,
49
+ capabilities: () => [...frozen],
50
+ list: spec.list,
51
+ keyOf: spec.keyOf,
52
+ cursorOf: spec.cursorOf,
53
+ compareCursor: spec.compareCursor,
54
+ ...(typeof spec.listComments === 'function' ? { listComments: spec.listComments } : {}),
55
+ ...(typeof spec.acknowledge === 'function' ? { acknowledge: spec.acknowledge } : {}),
56
+ })
57
+ }
58
+
59
+ export function requireCapability(provider, capability) {
60
+ if (!provider || !provider.capabilities().includes(capability)) {
61
+ throw new CapabilityError(provider && provider.name || 'unknown', capability)
62
+ }
63
+ const method = CAPABILITY_METHOD[capability]
64
+ return method ? provider[method] : true
65
+ }
66
+
67
+ function stable(value) {
68
+ if (Array.isArray(value)) return value.map(stable)
69
+ if (value && typeof value === 'object') {
70
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, stable(value[key])]))
71
+ }
72
+ return value
73
+ }
74
+
75
+ function labelNames(item, ackLabel) {
76
+ const excluded = String(ackLabel || '').toLowerCase()
77
+ return (Array.isArray(item.labels) ? item.labels : [])
78
+ .map((label) => String(label && label.name || label || '').trim())
79
+ .filter(Boolean)
80
+ .filter((name) => name.toLowerCase() !== excluded)
81
+ .sort((left, right) => left.localeCompare(right))
82
+ }
83
+
84
+ export function issueCursor(item = {}, options = {}) {
85
+ const semantic = {
86
+ title: String(item.title || ''),
87
+ body: String(item.body || ''),
88
+ state: String(item.state || ''),
89
+ state_reason: item.state_reason || null,
90
+ author: String(item.user && item.user.login || ''),
91
+ assignees: (Array.isArray(item.assignees) ? item.assignees : []).map((user) => String(user && user.login || '')).sort(),
92
+ labels: labelNames(item, options.ackLabel),
93
+ comments: item.comments === undefined ? null : Number(item.comments) || 0,
94
+ draft: item.draft === true,
95
+ pr: Boolean(item.pull_request),
96
+ }
97
+ return 'h:' + createHash('sha256').update(JSON.stringify(stable(semantic))).digest('hex').slice(0, 20)
98
+ }
99
+
100
+ export function issueKey(item) {
101
+ return `issue:${String(item && item.number || '')}`
102
+ }
103
+
104
+ function compareCursor(left, right) {
105
+ return left === right
106
+ }
107
+
108
+ function ghEnvValue(env) {
109
+ return typeof env === 'function' ? env() : env
110
+ }
111
+
112
+ async function githubAcknowledge(context, run, env) {
113
+ const { repo, number, label, note = '' } = context
114
+ const call = async (args) => run('gh', args, { timeoutMs: 20000, env: ghEnvValue(env) })
115
+ const ensured = await call(['api', '-X', 'POST', `repos/${repo}/labels`, '-f', `name=${label}`, '-f', 'color=ededed'])
116
+ if (ensured.code !== 0 && !/422|already exists/i.test(String(ensured.stderr || ''))) {
117
+ return { ok: false, stage: 'ensure-label', error: redact(ensured.stderr).slice(0, 240) }
118
+ }
119
+ const labeled = await call(['api', '-X', 'POST', `repos/${repo}/issues/${number}/labels`, '-f', `labels[]=${label}`])
120
+ if (labeled.code !== 0) return { ok: false, stage: 'label', error: redact(labeled.stderr).slice(0, 240) }
121
+ if (note) {
122
+ const commented = await call(['api', '-X', 'POST', `repos/${repo}/issues/${number}/comments`, '-f', `body=${note}`])
123
+ if (commented.code !== 0) return { ok: false, stage: 'comment', error: redact(commented.stderr).slice(0, 240) }
124
+ }
125
+ const readback = await call(['api', `repos/${repo}/issues/${number}`])
126
+ if (readback.code !== 0) return { ok: false, stage: 'readback', error: redact(readback.stderr).slice(0, 240) }
127
+ try {
128
+ return { ok: true, cursor: issueCursor(JSON.parse(String(readback.stdout || '')), { ackLabel: label }) }
129
+ } catch {
130
+ return { ok: false, stage: 'readback', error: 'post-ack issue is not valid JSON' }
131
+ }
132
+ }
133
+
134
+ export function createGithubProvider(options = {}) {
135
+ const run = options.run
136
+ if (typeof run !== 'function') throw new TypeError('createGithubProvider requires run')
137
+ const env = options.env || {}
138
+ return defineProvider({
139
+ name: 'github',
140
+ keyOf: issueKey,
141
+ cursorOf: issueCursor,
142
+ compareCursor,
143
+ list: async ({ repo, etag = '', perPage = 20 } = {}) => {
144
+ const size = Math.max(1, Math.min(100, Number(perPage) || 20))
145
+ const args = ['api', '--include', `repos/${repo}/issues?state=all&sort=updated&direction=desc&per_page=${size}`]
146
+ if (etag) args.push('-H', 'If-None-Match: ' + etag)
147
+ const res = await run('gh', args, { timeoutMs: 45000, env: ghEnvValue(env) })
148
+ const parsed = parseGhInclude(res.stdout)
149
+ if (res.code !== 0) {
150
+ return { ok: false, status: parsed.status, code: res.code, error: redact(res.stderr || res.stdout).slice(0, 240) }
151
+ }
152
+ let items
153
+ try {
154
+ const body = String(parsed.body || '').trim()
155
+ items = body ? JSON.parse(body) : []
156
+ } catch {
157
+ return { ok: false, status: parsed.status, error: 'non-json body', body: parsed.body }
158
+ }
159
+ if (!Array.isArray(items)) return { ok: false, status: parsed.status, error: 'body is not an array', body: parsed.body }
160
+ return {
161
+ ok: true, items, truncated: items.length >= size,
162
+ status: parsed.status, etag: parsed.etag, body: parsed.body,
163
+ remaining: parsed.remaining, resetAt: parsed.resetAt, retryAfter: parsed.retryAfter,
164
+ pollInterval: parsed.pollInterval,
165
+ }
166
+ },
167
+ acknowledge: (context) => githubAcknowledge(context, run, env),
168
+ ...(typeof options.listComments === 'function' ? { listComments: options.listComments } : {}),
169
+ })
170
+ }
171
+
172
+ export function createGiteeProvider(options = {}) {
173
+ const token = String(options.token || '')
174
+ const fetchImpl = options.fetchImpl || globalThis.fetch
175
+ return defineProvider({
176
+ name: 'gitee',
177
+ keyOf: issueKey,
178
+ cursorOf: issueCursor,
179
+ compareCursor,
180
+ list: ({ repo, perPage = 20, since = '' } = {}) => listGiteeItems({ repo, token, perPage, since, fetchImpl }),
181
+ listComments: ({ repo, item, selfLogin = '' } = {}) => fetchGiteeLastComment({
182
+ repo, token, item, selfLogin, fetchImpl, withStatus: true,
183
+ }),
184
+ acknowledge: async ({ repo, number, label, note = '', kind = 'issue' }) => {
185
+ const ensured = await ensureGiteeLabel({ repo, token, label, fetchImpl })
186
+ if (!ensured.ok) return { ok: false, stage: 'ensure-label', ...ensured }
187
+ const labeled = await addGiteeLabel({ repo, token, number, label, fetchImpl })
188
+ if (!labeled.ok) return { ok: false, stage: 'label', error: labeled.error }
189
+ if (note) {
190
+ const commented = await addGiteeComment({ repo, token, number, body: note, kind, fetchImpl })
191
+ if (!commented.ok) return { ok: false, stage: 'comment', error: commented.error }
192
+ }
193
+ const readback = await getGiteeItem({ repo, number, kind, token, fetchImpl })
194
+ if (!readback.ok) return { ok: false, stage: 'readback', error: readback.error }
195
+ return { ok: true, cursor: issueCursor(readback.item, { ackLabel: label }), labelCreated: ensured.created === true }
196
+ },
197
+ })
198
+ }
199
+
200
+ export async function runProviderConformance(provider) {
201
+ const checks = []
202
+ const check = (name, ok) => checks.push({ name, ok: Boolean(ok) })
203
+ check('name', typeof provider.name === 'string' && provider.name.length > 0)
204
+ for (const method of ['list', 'keyOf', 'cursorOf', 'compareCursor']) check(`required:${method}`, typeof provider[method] === 'function')
205
+ check('keyOf', typeof provider.keyOf(sampleConformanceItem()) === 'string')
206
+ const cursor = provider.cursorOf(sampleConformanceItem())
207
+ check('cursorOf', (typeof cursor === 'string' && cursor) || Number.isSafeInteger(cursor))
208
+ check('compare:same', provider.compareCursor(cursor, cursor) === true)
209
+ check('compare:different', provider.compareCursor(cursor, cursor === 'different' ? 'other' : 'different') === false)
210
+ for (const capability of provider.capabilities()) {
211
+ const method = CAPABILITY_METHOD[capability]
212
+ if (method) check(`capability:${capability}`, typeof provider[method] === 'function')
213
+ }
214
+ const listed = await provider.list({ repo: 'o/r', perPage: 1 })
215
+ check('list:structured', listed && listed.ok === true && Array.isArray(listed.items))
216
+ return checks
217
+ }
218
+
219
+ function sampleConformanceItem() {
220
+ return { number: 1, title: 'conformance', state: 'open', labels: [], assignees: [] }
221
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * 水位 v2 · 交付房。
3
+ *
4
+ * 发送与状态提交之间的唯一事务边界:没有明确成功回执,就不写 delivered;
5
+ * ack 没有处置后的 cursor,就不写 handled。其余房间不得绕过这里直接记账。
6
+ */
7
+ import { deliver as commitDelivered, handle as commitHandled } from './watermark-state.js'
8
+
9
+ function errorText(error) {
10
+ return String(error && error.message || error || 'unknown error').slice(0, 240)
11
+ }
12
+
13
+ function atTime(value) {
14
+ return value === undefined ? new Date().toISOString() : String(value)
15
+ }
16
+
17
+ export async function deliverBatch({ state, listed = [], send, at } = {}) {
18
+ const batch = Array.isArray(listed) ? listed.filter(Boolean) : []
19
+ if (batch.length === 0) return { status: 'empty', state, deliveredKeys: [], ignoredKeys: [] }
20
+ if (typeof send !== 'function') throw new TypeError('deliverBatch requires send')
21
+
22
+ let receipt
23
+ try { receipt = await send(batch) } catch (error) {
24
+ return { status: 'failed', state, error: errorText(error), deliveredKeys: [], ignoredKeys: [] }
25
+ }
26
+ if (!receipt || receipt.ok !== true) {
27
+ return {
28
+ status: receipt && receipt.busy === true ? 'busy' : 'failed',
29
+ state,
30
+ error: errorText(receipt && receipt.error || 'delivery was not acknowledged'),
31
+ deliveredKeys: [], ignoredKeys: [],
32
+ }
33
+ }
34
+
35
+ return commitDeliveryReceipt({ state, listed: batch, receipt, at })
36
+ }
37
+
38
+ export function commitDeliveryReceipt({ state, listed = [], receipt, at } = {}) {
39
+ const batch = Array.isArray(listed) ? listed.filter(Boolean) : []
40
+ const byKey = new Map(batch.map((record) => [String(record.key), record]))
41
+ const requested = receipt.deliveredKeys === undefined
42
+ ? [...byKey.keys()]
43
+ : (Array.isArray(receipt.deliveredKeys) ? receipt.deliveredKeys.map(String) : [])
44
+ const deliveredKeys = []
45
+ const ignoredKeys = []
46
+ const seen = new Set()
47
+ for (const key of requested) {
48
+ if (seen.has(key)) continue
49
+ seen.add(key)
50
+ if (!byKey.has(key)) { ignoredKeys.push(key); continue }
51
+ deliveredKeys.push(key)
52
+ }
53
+ if (deliveredKeys.length === 0) {
54
+ return { status: 'failed', state, error: 'no valid delivered keys in receipt', deliveredKeys, ignoredKeys }
55
+ }
56
+
57
+ let next = state
58
+ const atIso = atTime(at)
59
+ for (const key of deliveredKeys) {
60
+ const record = byKey.get(key)
61
+ next = commitDelivered(next, key, record.cursor, { round: next.round + 1, at: atIso })
62
+ }
63
+ return { status: 'delivered', state: next, deliveredKeys, ignoredKeys }
64
+ }
65
+
66
+ export async function acknowledgeBatch({ state, items = [], acknowledge, at } = {}) {
67
+ const batch = Array.isArray(items) ? items.filter(Boolean) : []
68
+ if (typeof acknowledge !== 'function' && batch.length > 0) throw new TypeError('acknowledgeBatch requires acknowledge')
69
+ let next = state
70
+ const results = []
71
+ const atIso = atTime(at)
72
+
73
+ for (const record of batch) {
74
+ const key = String(record.key)
75
+ let receipt
76
+ try {
77
+ receipt = await acknowledge({ ...record, ...(record.context || {}) })
78
+ } catch (error) {
79
+ results.push({ key, ok: false, error: errorText(error) })
80
+ continue
81
+ }
82
+ if (!receipt || receipt.ok !== true) {
83
+ results.push({ key, ok: false, error: errorText(receipt && receipt.error || 'ack was not acknowledged') })
84
+ continue
85
+ }
86
+ const postCursor = receipt.cursor
87
+ const validCursor = (typeof postCursor === 'string' && postCursor)
88
+ || (typeof postCursor === 'number' && Number.isSafeInteger(postCursor) && postCursor >= 0)
89
+ if (!validCursor) {
90
+ results.push({ key, ok: false, error: 'ack receipt must include post-ack cursor' })
91
+ continue
92
+ }
93
+ next = commitHandled(next, key, postCursor, { round: next.round + 1, at: atIso })
94
+ results.push({ key, ok: true, cursor: postCursor })
95
+ }
96
+ return { state: next, results }
97
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * 单人设置草稿状态。
3
+ *
4
+ * 只维护 base/value/revision 与 clean/editing 两态;保存、持久化和并发合并由调用方负责。
5
+ * 所有转换都复制输入并返回深冻结的新对象,调用方不能通过草稿回写已保存配置。
6
+ */
7
+
8
+ function isRecord(value) {
9
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
10
+ }
11
+
12
+ function hasOwn(value, key) {
13
+ return isRecord(value) && Object.prototype.hasOwnProperty.call(value, key)
14
+ }
15
+
16
+ function cloneValue(value) {
17
+ if (Array.isArray(value)) return value.map(cloneValue)
18
+ if (!isRecord(value)) return value
19
+ const copy = {}
20
+ for (const [key, child] of Object.entries(value)) copy[key] = cloneValue(child)
21
+ return copy
22
+ }
23
+
24
+ function deepFreeze(value, seen = new WeakSet()) {
25
+ if (!value || typeof value !== 'object' || seen.has(value)) return value
26
+ seen.add(value)
27
+ for (const child of Object.values(value)) deepFreeze(child, seen)
28
+ return Object.freeze(value)
29
+ }
30
+
31
+ function equal(left, right) {
32
+ if (Object.is(left, right)) return true
33
+ if (Array.isArray(left) || Array.isArray(right)) {
34
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false
35
+ return left.every((value, index) => equal(value, right[index]))
36
+ }
37
+ if (!isRecord(left) || !isRecord(right)) return false
38
+ const leftKeys = Object.keys(left)
39
+ const rightKeys = Object.keys(right)
40
+ if (leftKeys.length !== rightKeys.length) return false
41
+ return leftKeys.every((key) => hasOwn(right, key) && equal(left[key], right[key]))
42
+ }
43
+
44
+ function revisionOf(value) {
45
+ const revision = value === undefined ? 0 : value
46
+ if (!Number.isSafeInteger(revision) || revision < 0) {
47
+ throw new TypeError('revision must be a non-negative safe integer')
48
+ }
49
+ return revision
50
+ }
51
+
52
+ function optionsOf(value) {
53
+ if (value === undefined) return {}
54
+ if (Number.isSafeInteger(value)) return { revision: value }
55
+ if (!isRecord(value)) throw new TypeError('draft options must be an object or revision')
56
+ return value
57
+ }
58
+
59
+ function stateOf(value) {
60
+ if (!isRecord(value) || !hasOwn(value, 'base') || !hasOwn(value, 'value')) {
61
+ throw new TypeError('a draft created by createDraft is required')
62
+ }
63
+ return value
64
+ }
65
+
66
+ /**
67
+ * 从已保存值建立草稿。options.value 可恢复未保存值,options.revision 记录基线版本。
68
+ * value 与 base 深度相等时是 clean,否则恢复为 editing。
69
+ */
70
+ export function createDraft(saved, options) {
71
+ const source = optionsOf(options)
72
+ const value = hasOwn(source, 'value') ? source.value : saved
73
+ const dirty = !equal(value, saved)
74
+ return deepFreeze({
75
+ base: cloneValue(saved),
76
+ value: cloneValue(value),
77
+ revision: revisionOf(source.revision),
78
+ phase: dirty ? 'editing' : 'clean',
79
+ dirty,
80
+ })
81
+ }
82
+
83
+ /**
84
+ * 用完整新值编辑草稿;options.merge=true 时把 changes 作为浅补丁合并到当前对象值。
85
+ * 编辑回 base 会自动回到 clean;重复编辑也不修改旧状态。
86
+ */
87
+ export function editDraft(draft, changes, options) {
88
+ const state = stateOf(draft)
89
+ const source = optionsOf(options)
90
+ let value = cloneValue(changes)
91
+ if (source.merge === true) {
92
+ if (!isRecord(state.value) || !isRecord(changes)) {
93
+ throw new TypeError('merge editing requires object draft values and changes')
94
+ }
95
+ value = { ...cloneValue(state.value), ...cloneValue(changes) }
96
+ }
97
+ const base = hasOwn(source, 'base') ? source.base : state.base
98
+ const revision = hasOwn(source, 'revision') ? source.revision : state.revision
99
+ return createDraft(base, { value, revision })
100
+ }
101
+
102
+ /**
103
+ * 放弃未保存内容并回到 clean。默认恢复 base;options.saved 可改用最新服务端值,
104
+ * options.revision 可同时推进基线版本。
105
+ */
106
+ export function clearDraft(draft, options) {
107
+ const state = stateOf(draft)
108
+ const source = optionsOf(options)
109
+ const saved = hasOwn(source, 'saved') ? source.saved : state.base
110
+ const revision = hasOwn(source, 'revision') ? source.revision : state.revision
111
+ return createDraft(saved, { revision })
112
+ }