dsh-session-superagent 0.10.12 → 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,120 @@
1
+ /**
2
+ * 随包 skill 的严格解析与模型可见工具契约校验。
3
+ *
4
+ * 文件读取由调用方注入;本模块不直接访问磁盘、环境或宿主服务。
5
+ */
6
+ export const GITHUB_SKILL_NAME = 'dsh-session-superagent-github'
7
+ export const GITHUB_SKILL_PATH = 'skills/dsh-session-superagent-github/SKILL.md'
8
+
9
+ export class SkillPackError extends Error {
10
+ constructor(code, message, { path = 'SKILL.md', cause, missingTools = [], requiredTools = [] } = {}) {
11
+ super(message, cause === undefined ? undefined : { cause })
12
+ this.name = 'SkillPackError'
13
+ this.code = code
14
+ this.path = path
15
+ this.missingTools = Object.freeze([...missingTools])
16
+ this.requiredTools = Object.freeze([...requiredTools])
17
+ }
18
+ }
19
+
20
+ function sourcePath(options) {
21
+ if (typeof options === 'string') return options
22
+ return options && typeof options.path === 'string' ? options.path : 'SKILL.md'
23
+ }
24
+
25
+ export function parseSkillPack(source, options = {}) {
26
+ const path = sourcePath(options)
27
+ if (typeof source !== 'string' || !source.trim()) {
28
+ throw new SkillPackError('SKILL_EMPTY', `Empty skill pack: ${path}`, { path })
29
+ }
30
+ const text = source.replaceAll('\r\n', '\n')
31
+ // 与随包格式约定一致:只允许 name 与 description 两个字段,且正文前留一空行。
32
+ const match = /^---\nname: ([^\n]+)\ndescription: ([^\n]+)\n---\n\n([\s\S]*)$/.exec(text)
33
+ if (!match) throw new SkillPackError('SKILL_FRONTMATTER_INVALID', `Invalid skill pack: ${path}`, { path })
34
+ const [, name, rawDescription, content] = match
35
+ const description = rawDescription.trim()
36
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) {
37
+ throw new SkillPackError('SKILL_NAME_INVALID', `Invalid skill name in ${path}: ${name}`, { path })
38
+ }
39
+ if (!description) throw new SkillPackError('SKILL_DESCRIPTION_EMPTY', `Empty skill description: ${path}`, { path })
40
+ if (!content.trim()) throw new SkillPackError('SKILL_CONTENT_EMPTY', `Empty skill content: ${path}`, { path })
41
+ return Object.freeze({ name, description, content, path })
42
+ }
43
+
44
+ export function loadSkillPack(path, readFile) {
45
+ if (typeof readFile !== 'function') throw new TypeError('loadSkillPack requires readFile')
46
+ let source
47
+ try {
48
+ source = readFile(path, 'utf8')
49
+ } catch (error) {
50
+ throw new SkillPackError('SKILL_READ_FAILED', `Cannot read skill pack: ${path}`, { path, cause: error })
51
+ }
52
+ return parseSkillPack(source, { path })
53
+ }
54
+
55
+ /** Return every referenced plugin tool once, in first-appearance order. */
56
+ export function skillToolReferences(packOrContent) {
57
+ const content = packOrContent && typeof packOrContent === 'object'
58
+ ? String(packOrContent.content || '')
59
+ : String(packOrContent || '')
60
+ const names = new Set()
61
+ for (const match of content.matchAll(/\b(?:github|repo_here|watch_[a-z][a-z0-9_]*)\b/g)) names.add(match[0])
62
+ return Object.freeze([...names])
63
+ }
64
+
65
+ function availableToolNames(tools) {
66
+ if (tools == null) return new Set()
67
+ if (tools instanceof Map) return new Set([...tools.keys()].map(String))
68
+ if (typeof tools !== 'string' && typeof tools[Symbol.iterator] === 'function') {
69
+ const names = new Set()
70
+ for (const tool of tools) {
71
+ if (typeof tool === 'string') names.add(tool)
72
+ else if (tool && typeof tool.name === 'string') names.add(tool.name)
73
+ }
74
+ return names
75
+ }
76
+ if (typeof tools === 'object') return new Set(Object.keys(tools))
77
+ throw new TypeError('available tools must be an iterable, Map, or object')
78
+ }
79
+
80
+ export function validateSkillPack(packOrSource, availableTools, options = {}) {
81
+ const pack = typeof packOrSource === 'string' ? parseSkillPack(packOrSource, options) : packOrSource
82
+ const path = pack && typeof pack.path === 'string' ? pack.path : sourcePath(options)
83
+ if (!pack || typeof pack.name !== 'string' || typeof pack.content !== 'string' || !pack.content.trim()) {
84
+ throw new SkillPackError('SKILL_INVALID', `Invalid parsed skill pack: ${path}`, { path })
85
+ }
86
+ if (options.expectedName && pack.name !== options.expectedName) {
87
+ throw new SkillPackError('SKILL_NAME_MISMATCH', `Skill ${pack.name} must be named ${options.expectedName}`, { path })
88
+ }
89
+
90
+ const tools = skillToolReferences(pack)
91
+ const available = availableToolNames(availableTools)
92
+ const missingTools = tools.filter((name) => !available.has(name))
93
+ if (missingTools.length) {
94
+ throw new SkillPackError(
95
+ 'SKILL_TOOL_UNKNOWN',
96
+ `Skill ${pack.name} references unregistered tools: ${missingTools.join(', ')}`,
97
+ { path, missingTools },
98
+ )
99
+ }
100
+
101
+ const requiredTools = Array.isArray(options.requiredTools) ? options.requiredTools.map(String) : []
102
+ const unreferenced = requiredTools.filter((name) => !tools.includes(name))
103
+ if (unreferenced.length) {
104
+ throw new SkillPackError(
105
+ 'SKILL_TOOL_UNREFERENCED',
106
+ `Skill ${pack.name} does not reference required tools: ${unreferenced.join(', ')}`,
107
+ { path, requiredTools: unreferenced },
108
+ )
109
+ }
110
+ return Object.freeze({ ok: true, name: pack.name, tools })
111
+ }
112
+
113
+ export function validateGithubSkillPack(packOrSource, availableTools, options = {}) {
114
+ const requiredTools = [...new Set(['github', ...(options.requiredTools || [])])]
115
+ return validateSkillPack(packOrSource, availableTools, {
116
+ ...options,
117
+ expectedName: GITHUB_SKILL_NAME,
118
+ requiredTools,
119
+ })
120
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Source 扩展房:只负责 provider 的注册、查找与能力检查。
3
+ *
4
+ * provider 的网络与凭证仍由 data-provider 的显式端口注入;这里不读环境、
5
+ * 不发起网络请求,也不保存宿主状态。注册表实例之间完全隔离。
6
+ */
7
+ import {
8
+ CapabilityError,
9
+ defineProvider,
10
+ requireCapability as requireProviderCapability,
11
+ } from './data-provider.js'
12
+
13
+ export { CapabilityError }
14
+
15
+ export class SourceRegistryError extends Error {
16
+ constructor(message, code, details = {}) {
17
+ super(message)
18
+ this.name = 'SourceRegistryError'
19
+ this.code = code
20
+ Object.assign(this, details)
21
+ }
22
+ }
23
+
24
+ export class DuplicateProviderError extends SourceRegistryError {
25
+ constructor(provider) {
26
+ super(`provider already registered: ${provider}`, 'PROVIDER_DUPLICATE', { provider })
27
+ this.name = 'DuplicateProviderError'
28
+ }
29
+ }
30
+
31
+ export class ProviderNotFoundError extends SourceRegistryError {
32
+ constructor(provider) {
33
+ super(`provider not registered: ${provider}`, 'PROVIDER_NOT_FOUND', { provider })
34
+ this.name = 'ProviderNotFoundError'
35
+ }
36
+ }
37
+
38
+ function providerName(spec) {
39
+ if (!spec || typeof spec !== 'object') throw new TypeError('provider must be an object')
40
+ const name = typeof spec.name === 'string' ? spec.name.trim() : ''
41
+ if (!name) throw new TypeError('provider name is required')
42
+ return name
43
+ }
44
+
45
+ function normalizeProvider(spec) {
46
+ const name = providerName(spec)
47
+ // defineProvider() 已经产出一个带 capabilities() 的完整 provider。保留它的
48
+ // 对象身份,但重新经过 defineProvider 校验,避免手工伪造对象绕过必需针脚。
49
+ if (typeof spec.capabilities === 'function') {
50
+ const capabilities = spec.capabilities()
51
+ if (!Array.isArray(capabilities)) {
52
+ throw new TypeError(`provider ${name} capabilities() must return an array`)
53
+ }
54
+ defineProvider({ ...spec, name, capabilities })
55
+ return spec
56
+ }
57
+ return defineProvider({ ...spec, name })
58
+ }
59
+
60
+ /** A deterministic, instance-local registry of data-provider implementations. */
61
+ export class SourceRegistry {
62
+ #providers = new Map()
63
+
64
+ constructor(providers = []) {
65
+ if (providers == null) providers = []
66
+ if (typeof providers[Symbol.iterator] !== 'function') {
67
+ throw new TypeError('SourceRegistry providers must be iterable')
68
+ }
69
+ for (const provider of providers) this.register(provider)
70
+ }
71
+
72
+ register(spec) {
73
+ const provider = normalizeProvider(spec)
74
+ if (this.#providers.has(provider.name)) throw new DuplicateProviderError(provider.name)
75
+ this.#providers.set(provider.name, provider)
76
+ return provider
77
+ }
78
+
79
+ get(name, capability) {
80
+ const key = typeof name === 'string' ? name.trim() : ''
81
+ const provider = this.#providers.get(key)
82
+ if (!provider) throw new ProviderNotFoundError(key || String(name || 'unknown'))
83
+ if (capability !== undefined) requireProviderCapability(provider, capability)
84
+ return provider
85
+ }
86
+
87
+ list() {
88
+ const providers = [...this.#providers.values()]
89
+ providers.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0)
90
+ return Object.freeze(providers)
91
+ }
92
+
93
+ requireCapability(name, capability) {
94
+ return requireProviderCapability(this.get(name), capability)
95
+ }
96
+ }
97
+
98
+ export function createSourceRegistry(providers = []) {
99
+ return new SourceRegistry(providers)
100
+ }
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Thread 订阅房。
3
+ *
4
+ * 只维护 Thread → Ticket/session 归属与事件去重,不直接唤醒、投递或执行。
5
+ * routeThreadEvent 返回 deliver / resume / eval / ignore 决策和新的持久化状态;
6
+ * 宿主需在单写者事务中提交 state,才能跨重启保持幂等。
7
+ */
8
+ export const THREAD_SUBSCRIPTION_VERSION = 1
9
+
10
+ const DISPOSITIONS = new Set(['deliver', 'resume', 'eval', 'ignore'])
11
+ const TICKET_STATUSES = new Set(['open', 'assigned', 'waiting', 'ended'])
12
+
13
+ function isObject(value) {
14
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
15
+ }
16
+
17
+ function requiredText(value, name) {
18
+ if (value === undefined || value === null) throw new TypeError(`${name} is required`)
19
+ const text = String(value).trim()
20
+ if (!text) throw new TypeError(`${name} is required`)
21
+ return text
22
+ }
23
+
24
+ function eventAt(value) {
25
+ return value === undefined ? new Date().toISOString() : requiredText(value, 'at')
26
+ }
27
+
28
+ function ticketStatus(value) {
29
+ const status = value === undefined ? 'open' : requiredText(value, 'ticketStatus')
30
+ if (!TICKET_STATUSES.has(status)) throw new TypeError(`unsupported ticketStatus: ${status}`)
31
+ return status
32
+ }
33
+
34
+ function endReason(value, status) {
35
+ if (status !== 'ended' || value === undefined || value === null) return null
36
+ return requiredText(value, 'endReason')
37
+ }
38
+
39
+ function cloneSubscription(row) {
40
+ return isObject(row) ? { ...row } : row
41
+ }
42
+
43
+ function cloneRoutedEvent(row) {
44
+ return isObject(row) ? { ...row } : row
45
+ }
46
+
47
+ function cloneRows(rows, cloneRow) {
48
+ if (!isObject(rows)) return {}
49
+ return Object.fromEntries(Object.entries(rows).map(([key, row]) => [key, cloneRow(row)]))
50
+ }
51
+
52
+ function assertVersion(version) {
53
+ if (version !== undefined && version !== THREAD_SUBSCRIPTION_VERSION) {
54
+ throw new Error(`threadSubscriptionVersion ${version} is newer than supported ${THREAD_SUBSCRIPTION_VERSION}`)
55
+ }
56
+ }
57
+
58
+ export function createThreadSubscriptionState(fields = {}) {
59
+ const source = isObject(fields) ? fields : {}
60
+ assertVersion(source.threadSubscriptionVersion)
61
+ return {
62
+ ...source,
63
+ threadSubscriptionVersion: THREAD_SUBSCRIPTION_VERSION,
64
+ subscriptions: cloneRows(source.subscriptions, cloneSubscription),
65
+ seenEvents: cloneRows(source.seenEvents, cloneRoutedEvent),
66
+ }
67
+ }
68
+
69
+ function asState(input) {
70
+ if (input === undefined || input === null) return createThreadSubscriptionState()
71
+ if (!isObject(input)) throw new TypeError('state must be an object')
72
+ assertVersion(input.threadSubscriptionVersion)
73
+ return input.threadSubscriptionVersion === undefined ? createThreadSubscriptionState(input) : input
74
+ }
75
+
76
+ export function subscribe(input, spec = {}) {
77
+ const state = asState(input)
78
+ if (!isObject(spec)) throw new TypeError('subscription must be an object')
79
+ const threadKey = requiredText(spec.threadKey, 'threadKey')
80
+ const ticketId = requiredText(spec.ticketId, 'ticketId')
81
+ const sessionId = requiredText(spec.sessionId, 'sessionId')
82
+ const previous = isObject(state.subscriptions[threadKey]) ? state.subscriptions[threadKey] : null
83
+
84
+ if (previous && previous.active === true) {
85
+ if (previous.ticketId === ticketId && previous.sessionId === sessionId) return state
86
+ throw new Error(`thread ${threadKey} already has an active subscription; unsubscribe before rebinding`)
87
+ }
88
+
89
+ const sameTicket = previous && previous.ticketId === ticketId
90
+ const status = ticketStatus(spec.ticketStatus ?? (sameTicket ? previous.ticketStatus : undefined))
91
+ const subscription = {
92
+ threadKey,
93
+ ticketId,
94
+ sessionId,
95
+ active: true,
96
+ createdAt: eventAt(spec.at),
97
+ ticketStatus: status,
98
+ endReason: endReason(spec.endReason ?? (sameTicket ? previous.endReason : null), status),
99
+ }
100
+ return {
101
+ ...state,
102
+ subscriptions: { ...state.subscriptions, [threadKey]: subscription },
103
+ }
104
+ }
105
+
106
+ export function unsubscribe(input, threadKey) {
107
+ const state = asState(input)
108
+ const key = requiredText(threadKey, 'threadKey')
109
+ const previous = isObject(state.subscriptions[key]) ? state.subscriptions[key] : null
110
+ if (!previous || previous.active !== true) return state
111
+ return {
112
+ ...state,
113
+ subscriptions: {
114
+ ...state.subscriptions,
115
+ [key]: { ...previous, threadKey: key, active: false },
116
+ },
117
+ }
118
+ }
119
+
120
+ export function syncTicketState(input, threadKey, patch = {}) {
121
+ const state = asState(input)
122
+ const key = requiredText(threadKey, 'threadKey')
123
+ if (!isObject(patch)) throw new TypeError('ticket patch must be an object')
124
+ const previous = isObject(state.subscriptions[key]) ? state.subscriptions[key] : null
125
+ if (!previous) throw new Error(`cannot sync ticket for unknown thread: ${key}`)
126
+ const status = ticketStatus(requiredText(patch.status, 'status'))
127
+ const reason = endReason(patch.endReason, status)
128
+ if (previous.ticketStatus === status && (previous.endReason ?? null) === reason) return state
129
+ return {
130
+ ...state,
131
+ subscriptions: {
132
+ ...state.subscriptions,
133
+ [key]: { ...previous, ticketStatus: status, endReason: reason },
134
+ },
135
+ }
136
+ }
137
+
138
+ function actorName(value) {
139
+ if (typeof value === 'string') return value.trim().toLowerCase()
140
+ if (isObject(value)) return actorName(value.type ?? value.kind ?? value.role)
141
+ return ''
142
+ }
143
+
144
+ function isHumanEvent(event) {
145
+ if (event.human === false) return false
146
+ const actor = actorName(event.actor ?? event.actorType ?? event.source)
147
+ // 非人 actor 优先于 human:true,冲突输入不得放大成执行生命周期操作。
148
+ if (actor) return actor === 'human'
149
+ return event.human === true
150
+ }
151
+
152
+ function isResumeRequested(event) {
153
+ const kind = String(event.type ?? event.kind ?? event.action ?? '').trim().toLowerCase()
154
+ return event.resume === true || kind === 'resume'
155
+ }
156
+
157
+ function eventIdentity(event) {
158
+ const threadKey = requiredText(event.threadKey, 'event.threadKey')
159
+ const eventId = requiredText(event.id ?? event.eventId, 'event.id')
160
+ return { threadKey, eventId, key: JSON.stringify([threadKey, eventId]) }
161
+ }
162
+
163
+ function ownership(row) {
164
+ return {
165
+ ticketId: row && typeof row.ticketId === 'string' ? row.ticketId : null,
166
+ sessionId: row && typeof row.sessionId === 'string' ? row.sessionId : null,
167
+ }
168
+ }
169
+
170
+ function decision(disposition, identity, row, state, { duplicate = false, reason } = {}) {
171
+ if (!DISPOSITIONS.has(disposition)) throw new Error(`unsupported thread event disposition: ${disposition}`)
172
+ return {
173
+ disposition,
174
+ threadKey: identity.threadKey,
175
+ eventId: identity.eventId,
176
+ ...ownership(row),
177
+ reason: reason || (duplicate ? 'duplicate-event' : 'subscribed-event'),
178
+ duplicate,
179
+ state,
180
+ }
181
+ }
182
+
183
+ export function routeThreadEvent(input, event = {}) {
184
+ const state = asState(input)
185
+ if (!isObject(event)) throw new TypeError('event must be an object')
186
+ const identity = eventIdentity(event)
187
+ const previous = isObject(state.seenEvents[identity.key]) ? state.seenEvents[identity.key] : null
188
+ if (previous) {
189
+ // 去重优先于当前订阅:取消或换绑后重投旧事件也不能改投新主人。
190
+ return decision('ignore', identity, previous, state, { duplicate: true })
191
+ }
192
+
193
+ const subscription = isObject(state.subscriptions[identity.threadKey])
194
+ && state.subscriptions[identity.threadKey].active === true
195
+ ? state.subscriptions[identity.threadKey]
196
+ : null
197
+ const human = isHumanEvent(event)
198
+ const explicitResume = human && isResumeRequested(event)
199
+ const ended = subscription && subscription.ticketStatus === 'ended'
200
+ const humanStopped = ended && subscription.endReason === 'human-stop'
201
+
202
+ let disposition
203
+ let reason
204
+ if (!subscription) {
205
+ disposition = 'eval'
206
+ reason = 'no-active-subscription'
207
+ } else if (!ended) {
208
+ // Ticket 只有 ended 才能 resume;其余状态的显式 resume 标记也仅作后续交付。
209
+ disposition = 'deliver'
210
+ reason = 'subscribed-event'
211
+ } else if (explicitResume) {
212
+ disposition = 'resume'
213
+ reason = 'explicit-human-resume'
214
+ } else if (humanStopped) {
215
+ disposition = 'ignore'
216
+ reason = 'human-stop'
217
+ } else if (human) {
218
+ disposition = 'resume'
219
+ reason = 'ended-human-comment'
220
+ } else {
221
+ disposition = 'eval'
222
+ reason = 'ended-non-human-event'
223
+ }
224
+
225
+ const routed = {
226
+ disposition,
227
+ threadKey: identity.threadKey,
228
+ eventId: identity.eventId,
229
+ ...ownership(subscription),
230
+ reason,
231
+ }
232
+ const next = {
233
+ ...state,
234
+ seenEvents: { ...state.seenEvents, [identity.key]: routed },
235
+ }
236
+ return decision(disposition, identity, subscription, next, { reason })
237
+ }