dsh-session-superagent 0.10.12 → 2.0.1

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,241 @@
1
+ /**
2
+ * 单用户执行房:规划 Ticket 的 Assignment,并通过宿主注入的 Executor 端口执行。
3
+ *
4
+ * 这里不创建 Session、工作区或子代理,也不回退到当前 Session。所有执行能力都必须
5
+ * 由 ExecutorAdapter 显式提供;领域状态只有在端口明确成功后才推进。
6
+ */
7
+ import { posix, win32 } from 'node:path'
8
+ import { assign as assignTicket } from './ticket-state.js'
9
+
10
+ const EXECUTOR_METHODS = Object.freeze(['start', 'prompt', 'status', 'stop'])
11
+ const ASSIGNMENT_STATUSES = new Set(['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 (typeof value !== 'string' || value.trim() === '') throw new TypeError(`${name} must be a non-empty string`)
19
+ return value
20
+ }
21
+
22
+ function positiveInteger(value, name) {
23
+ if (!Number.isSafeInteger(value) || value < 1) throw new TypeError(`${name} must be a positive safe integer`)
24
+ return value
25
+ }
26
+
27
+ /** 同时识别 POSIX 与 Windows 绝对路径;不做依赖宿主编译平台的路径归一化。 */
28
+ export function assertAbsoluteWorkdir(workdir) {
29
+ requiredText(workdir, 'workdir')
30
+ if (workdir.includes('\0') || (!posix.isAbsolute(workdir) && !win32.isAbsolute(workdir))) {
31
+ throw new TypeError('workdir must be an absolute path')
32
+ }
33
+ return workdir
34
+ }
35
+
36
+ /** Executor 是完整端口,任何能力缺失都显式失败,绝不静默换到别的执行体。 */
37
+ export function assertExecutorPort(executor) {
38
+ if (!isObject(executor)) throw new TypeError('executor port is required')
39
+ for (const method of EXECUTOR_METHODS) {
40
+ if (typeof executor[method] !== 'function') {
41
+ throw new TypeError(`executor port missing required method: ${method}`)
42
+ }
43
+ }
44
+ return executor
45
+ }
46
+
47
+ export function assertAssignment(assignment) {
48
+ if (!isObject(assignment)) throw new TypeError('assignment is required')
49
+ requiredText(assignment.id, 'assignment.id')
50
+ requiredText(assignment.ticketId, 'assignment.ticketId')
51
+ requiredText(assignment.sessionId, 'assignment.sessionId')
52
+ assertAbsoluteWorkdir(assignment.workdir)
53
+ if (!ASSIGNMENT_STATUSES.has(assignment.status)) {
54
+ throw new TypeError(`assignment.status must be one of: ${[...ASSIGNMENT_STATUSES].join(', ')}`)
55
+ }
56
+ positiveInteger(assignment.attempts, 'assignment.attempts')
57
+ return assignment
58
+ }
59
+
60
+ /** 创建第 sequence 次派工;attempts 只属于这一个 Assignment,不从旧派工继承。 */
61
+ export function createAssignment({ ticketId, sessionId, workdir, sequence = 1, attempts = 1 } = {}) {
62
+ requiredText(ticketId, 'ticketId')
63
+ requiredText(sessionId, 'sessionId')
64
+ positiveInteger(sequence, 'sequence')
65
+ positiveInteger(attempts, 'attempts')
66
+ return {
67
+ id: `assign:${ticketId}:${sequence}`,
68
+ ticketId,
69
+ sessionId,
70
+ workdir: assertAbsoluteWorkdir(workdir),
71
+ status: 'assigned',
72
+ attempts,
73
+ }
74
+ }
75
+
76
+ /** 显式重试同一派工;ended 是不可原地重开的终态。 */
77
+ export function retryAssignment(assignment) {
78
+ assertAssignment(assignment)
79
+ if (assignment.status === 'ended') throw new Error('ended assignment cannot be retried; create a new assignment')
80
+ if (assignment.attempts >= Number.MAX_SAFE_INTEGER) throw new RangeError('assignment.attempts cannot advance')
81
+ return { ...assignment, status: 'assigned', attempts: assignment.attempts + 1 }
82
+ }
83
+
84
+ /** 应用 Executor 回报的状态,不修改输入,也不允许 ended 被状态轮询重新打开。 */
85
+ export function transitionAssignment(assignment, status) {
86
+ assertAssignment(assignment)
87
+ if (!ASSIGNMENT_STATUSES.has(status)) throw new TypeError(`unknown assignment status: ${String(status)}`)
88
+ if (assignment.status === 'ended' && status !== 'ended') {
89
+ throw new Error('ended assignment cannot transition back to an active status')
90
+ }
91
+ return assignment.status === status ? assignment : { ...assignment, status }
92
+ }
93
+
94
+ function nextSequence(assignment) {
95
+ const match = /:(\d+)$/.exec(assignment.id)
96
+ if (!match) throw new TypeError('sequence is required when the previous assignment id has no numeric suffix')
97
+ const previous = Number(match[1])
98
+ if (!Number.isSafeInteger(previous) || previous >= Number.MAX_SAFE_INTEGER) {
99
+ throw new RangeError('assignment sequence cannot advance')
100
+ }
101
+ return previous + 1
102
+ }
103
+
104
+ /**
105
+ * 纯规划:新派工返回 action=start;活跃派工默认原样复用,显式 retry 才增加 attempts。
106
+ * 若 Ticket 已经由 ticket-state 的显式人工 resume 重新打开,旧 ended Assignment 不会
107
+ * 原地复活,而是生成下一 sequence。Ticket 的状态写入仍只走 ticket-state 公开 API。
108
+ */
109
+ export function planAssignment({
110
+ ticket,
111
+ assignment = null,
112
+ sessionId,
113
+ workdir,
114
+ retry = false,
115
+ sequence,
116
+ at,
117
+ eventId,
118
+ detail,
119
+ } = {}) {
120
+ if (!isObject(ticket)) throw new TypeError('ticket is required')
121
+ const ticketId = requiredText(ticket.id, 'ticket.id')
122
+ if (assignment !== null) {
123
+ assertAssignment(assignment)
124
+ if (assignment.ticketId !== ticketId) throw new TypeError('assignment.ticketId must match ticket.id')
125
+ }
126
+ if (typeof retry !== 'boolean') throw new TypeError('retry must be a boolean')
127
+
128
+ const nextSessionId = requiredText(sessionId ?? assignment?.sessionId, 'sessionId')
129
+ const nextWorkdir = assertAbsoluteWorkdir(workdir ?? assignment?.workdir)
130
+ let nextAssignment
131
+ let action
132
+
133
+ if (assignment === null) {
134
+ nextAssignment = createAssignment({
135
+ ticketId,
136
+ sessionId: nextSessionId,
137
+ workdir: nextWorkdir,
138
+ sequence: sequence ?? 1,
139
+ })
140
+ action = 'start'
141
+ } else if (assignment.status === 'ended') {
142
+ // assignTicket 会拒绝尚未经显式人工 resume 的 ended Ticket。
143
+ nextAssignment = createAssignment({
144
+ ticketId,
145
+ sessionId: nextSessionId,
146
+ workdir: nextWorkdir,
147
+ sequence: sequence ?? nextSequence(assignment),
148
+ })
149
+ action = 'start'
150
+ } else {
151
+ if (nextSessionId !== assignment.sessionId) throw new TypeError('an active assignment cannot change sessionId')
152
+ if (nextWorkdir !== assignment.workdir) throw new TypeError('an active assignment cannot change workdir')
153
+ nextAssignment = retry ? retryAssignment(assignment) : assignment
154
+ action = retry ? 'retry' : 'reuse'
155
+ }
156
+
157
+ let nextTicket = ticket
158
+ if (action === 'reuse' && nextAssignment.status === 'waiting') {
159
+ // 复用等待中的派工不等于重试,不能把 Ticket 悄悄激活。
160
+ if (ticket.status !== 'waiting'
161
+ || ticket.assignmentId !== nextAssignment.id
162
+ || ticket.ownerSessionId !== nextAssignment.sessionId
163
+ || ticket.workdir !== nextAssignment.workdir) {
164
+ throw new Error('retry is required to reactivate a waiting assignment')
165
+ }
166
+ } else {
167
+ nextTicket = assignTicket(ticket, {
168
+ sessionId: nextAssignment.sessionId,
169
+ workdir: nextAssignment.workdir,
170
+ assignmentId: nextAssignment.id,
171
+ at,
172
+ eventId,
173
+ detail,
174
+ })
175
+ }
176
+ return { ticket: nextTicket, assignment: nextAssignment, action }
177
+ }
178
+
179
+ function executionContext(ticket, assignment) {
180
+ if (!isObject(ticket)) throw new TypeError('ticket is required')
181
+ requiredText(ticket.id, 'ticket.id')
182
+ assertAssignment(assignment)
183
+ if (assignment.ticketId !== ticket.id) throw new TypeError('assignment.ticketId must match ticket.id')
184
+ return { ticket, assignment }
185
+ }
186
+
187
+ function assertActive(assignment) {
188
+ if (assignment.status === 'ended') throw new Error('ended assignment cannot execute')
189
+ }
190
+
191
+ function assertSuccessfulReceipt(receipt, method) {
192
+ if (isObject(receipt) && receipt.ok === false) {
193
+ throw new Error(String(receipt.error || `executor ${method} was not acknowledged`))
194
+ }
195
+ }
196
+
197
+ export async function startAssignment({ executor, ticket, assignment } = {}) {
198
+ assertExecutorPort(executor)
199
+ const context = executionContext(ticket, assignment)
200
+ assertActive(assignment)
201
+ const receipt = await executor.start(context)
202
+ assertSuccessfulReceipt(receipt, 'start')
203
+ return { ticket, assignment, receipt }
204
+ }
205
+
206
+ export async function promptAssignment({ executor, ticket, assignment, prompt, messageId } = {}) {
207
+ assertExecutorPort(executor)
208
+ const context = executionContext(ticket, assignment)
209
+ assertActive(assignment)
210
+ requiredText(prompt, 'prompt')
211
+ const receipt = await executor.prompt({ ...context, prompt, messageId })
212
+ assertSuccessfulReceipt(receipt, 'prompt')
213
+ return { ticket, assignment, receipt }
214
+ }
215
+
216
+ function receiptStatus(receipt) {
217
+ const status = typeof receipt === 'string' ? receipt : receipt?.status
218
+ if (!ASSIGNMENT_STATUSES.has(status)) {
219
+ throw new TypeError('executor status receipt must contain assigned, waiting, or ended')
220
+ }
221
+ return status
222
+ }
223
+
224
+ export async function statusAssignment({ executor, ticket, assignment } = {}) {
225
+ assertExecutorPort(executor)
226
+ const context = executionContext(ticket, assignment)
227
+ const receipt = await executor.status(context)
228
+ assertSuccessfulReceipt(receipt, 'status')
229
+ const nextAssignment = transitionAssignment(assignment, receiptStatus(receipt))
230
+ return { ticket, assignment: nextAssignment, receipt }
231
+ }
232
+
233
+ export async function stopAssignment({ executor, ticket, assignment, reason = 'stopped' } = {}) {
234
+ assertExecutorPort(executor)
235
+ const context = executionContext(ticket, assignment)
236
+ requiredText(reason, 'reason')
237
+ if (assignment.status === 'ended') return { ticket, assignment, receipt: null }
238
+ const receipt = await executor.stop({ ...context, reason })
239
+ assertSuccessfulReceipt(receipt, 'stop')
240
+ return { ticket, assignment: transitionAssignment(assignment, 'ended'), receipt }
241
+ }
@@ -0,0 +1,82 @@
1
+ /** 单用户 Executor 的 DSH 宿主适配;无宿主能力时显式失败,不回退当前会话。 */
2
+ import { randomUUID } from 'node:crypto'
3
+ import { isAbsolute } from 'node:path'
4
+ import { redact } from '../redact.js'
5
+
6
+ export function workerSessionId(ticketId) {
7
+ const id = String(ticketId || '').trim()
8
+ if (!id) throw new TypeError('ticketId is required')
9
+ return `worker-${id}`
10
+ }
11
+
12
+ function unwrap(result, sessionId) {
13
+ if (result && result.agent) return result.agent
14
+ const error = result && result.error
15
+ const wrapped = new Error(error && error.message || `session not available: ${sessionId}`)
16
+ wrapped.code = error && error.code || 'SESSION_UNAVAILABLE'
17
+ throw wrapped
18
+ }
19
+
20
+ export function createDshExecutor(ctx = {}) {
21
+ function requireHost(name) {
22
+ const service = ctx[name]
23
+ if (!service) throw new TypeError(`DSH host capability missing: ${name}`)
24
+ return service
25
+ }
26
+ async function resolve(sessionId) {
27
+ const controller = requireHost('sessionController')
28
+ if (typeof controller.resolveAgent !== 'function') throw new TypeError('DSH host capability missing: sessionController.resolveAgent')
29
+ return unwrap(await controller.resolveAgent(sessionId), sessionId)
30
+ }
31
+ return Object.freeze({
32
+ async start({ ticket, assignment } = {}) {
33
+ const workdir = String(assignment && assignment.workdir || ticket && ticket.workdir || '')
34
+ if (!isAbsolute(workdir)) throw new TypeError('executor workdir must be absolute')
35
+ const sessionId = workerSessionId(ticket && ticket.id)
36
+ const controller = requireHost('sessionController')
37
+ let result = await controller.resolveAgent(sessionId)
38
+ if (result && result.error && result.error.code === 'session/not-found') {
39
+ const registry = requireHost('workspaceRegistry')
40
+ if (typeof registry.create !== 'function') throw new TypeError('DSH host capability missing: workspaceRegistry.create')
41
+ const workspace = await registry.create(workdir)
42
+ if (typeof controller.create !== 'function') throw new TypeError('DSH host capability missing: sessionController.create')
43
+ await controller.create({ sessionId, workspaceId: workspace.id, agentPreset: 'standard' })
44
+ result = await controller.resolveAgent(sessionId)
45
+ }
46
+ const agent = unwrap(result, sessionId)
47
+ return { ok: true, sessionId: agent.id || sessionId, workdir }
48
+ },
49
+ async prompt({ ticket, prompt, messageId } = {}) {
50
+ const sessionId = workerSessionId(ticket && ticket.id)
51
+ const agent = await resolve(sessionId)
52
+ if (agent.status && agent.status !== 'idle') return { ok: false, busy: true, error: `worker busy: ${agent.status}`, sessionId }
53
+ const message = {
54
+ id: messageId || randomUUID(), role: 'user', source: { kind: 'user' },
55
+ content: [{ type: 'text', text: redact(String(prompt || '')) }],
56
+ }
57
+ if (typeof agent.followup === 'function') { await agent.followup(message); return { ok: true, via: 'followup', sessionId } }
58
+ if (typeof agent.steer === 'function') { await agent.steer(message); return { ok: true, via: 'steer', sessionId } }
59
+ const inbox = agent.inbox || agent.session && agent.session.inbox
60
+ if (inbox && typeof inbox.append === 'function') {
61
+ await inbox.append('next-turn', message)
62
+ return { ok: true, via: 'inbox.append', sessionId }
63
+ }
64
+ throw new TypeError('worker session has no followup/steer/inbox delivery port')
65
+ },
66
+ async status({ ticket } = {}) {
67
+ const sessionId = workerSessionId(ticket && ticket.id)
68
+ const agent = await resolve(sessionId)
69
+ const hostStatus = String(agent.status || '')
70
+ const status = hostStatus === 'running' ? 'assigned' : hostStatus === 'idle' ? 'waiting' : hostStatus === 'ended' ? 'ended' : null
71
+ if (!status) throw new TypeError(`unknown worker status: ${hostStatus || 'missing'}`)
72
+ return { sessionId, status, hostStatus }
73
+ },
74
+ async stop({ ticket, reason = '' } = {}) {
75
+ const sessionId = workerSessionId(ticket && ticket.id)
76
+ const agent = await resolve(sessionId)
77
+ if (typeof agent.cancel !== 'function') throw new TypeError('worker session has no cancel port')
78
+ await agent.cancel({ kind: 'user', reason: String(reason) }, { keepInbox: true })
79
+ return { ok: true, sessionId }
80
+ },
81
+ })
82
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * 极简 zh/en 文案房。
3
+ *
4
+ * - zh-CN / en-US 等标签归一到 zh / en,未知语言回退到 zh;
5
+ * - 当前语言缺键时回退到另一种语言(也可显式关闭);
6
+ * - 所有 {variable} 必须显式提供,缺参抛错,不留下半渲染文本;
7
+ * - 目录会被复制并冻结,withOverrides 返回新 translator。
8
+ */
9
+
10
+ export const SUPPORTED_LANGUAGES = Object.freeze(['zh', 'en'])
11
+ export const DEFAULT_LANGUAGE = 'zh'
12
+
13
+ const PLACEHOLDER = /\{([A-Za-z][A-Za-z0-9_]*)\}/g
14
+
15
+ export class MissingTemplateVariableError extends TypeError {
16
+ constructor(missing, context = {}) {
17
+ const where = context.key ? ` in ${context.key}` : ''
18
+ super(`missing template variable${missing.length === 1 ? '' : 's'}${where}: ${missing.join(', ')}`)
19
+ this.name = 'MissingTemplateVariableError'
20
+ this.code = 'I18N_VARIABLES_MISSING'
21
+ this.missing = Object.freeze([...missing])
22
+ this.key = context.key || null
23
+ this.language = context.language || null
24
+ }
25
+ }
26
+
27
+ export class TemplateNotFoundError extends Error {
28
+ constructor(key, languages) {
29
+ super(`template not found: ${key} (tried ${languages.join(', ')})`)
30
+ this.name = 'TemplateNotFoundError'
31
+ this.code = 'I18N_TEMPLATE_MISSING'
32
+ this.key = key
33
+ this.languages = Object.freeze([...languages])
34
+ }
35
+ }
36
+
37
+ function isRecord(value) {
38
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
39
+ }
40
+
41
+ function assertLanguage(language) {
42
+ if (!SUPPORTED_LANGUAGES.includes(language)) {
43
+ throw new RangeError(`catalog language must be zh or en; received ${String(language)}`)
44
+ }
45
+ }
46
+
47
+ function assertKey(key) {
48
+ if (typeof key !== 'string' || !key.trim()) throw new TypeError('template key must be a non-empty string')
49
+ return key
50
+ }
51
+
52
+ function assertTemplate(template, key, language) {
53
+ if (typeof template !== 'string' || !template.trim()) {
54
+ throw new TypeError(`template ${language}.${key} must be a non-empty string`)
55
+ }
56
+ return template
57
+ }
58
+
59
+ export function normalizeLanguage(language) {
60
+ const tag = String(language || '').trim().toLowerCase().replaceAll('_', '-')
61
+ if (tag === 'en' || tag.startsWith('en-')) return 'en'
62
+ if (tag === 'zh' || tag.startsWith('zh-')) return 'zh'
63
+ return DEFAULT_LANGUAGE
64
+ }
65
+
66
+ export function templateVariables(template) {
67
+ if (typeof template !== 'string') throw new TypeError('template must be a string')
68
+ return Object.freeze([...new Set([...template.matchAll(PLACEHOLDER)].map((match) => match[1]))])
69
+ }
70
+
71
+ export function interpolate(template, values = {}, context = {}) {
72
+ if (typeof template !== 'string') throw new TypeError('template must be a string')
73
+ if (!isRecord(values)) throw new TypeError('template values must be an object')
74
+ const variables = templateVariables(template)
75
+ const missing = variables.filter((key) => !Object.hasOwn(values, key) || values[key] === undefined || values[key] === null)
76
+ if (missing.length > 0) throw new MissingTemplateVariableError(missing, context)
77
+ return template.replace(PLACEHOLDER, (_, key) => String(values[key]))
78
+ }
79
+
80
+ function copyCatalogs(catalogs) {
81
+ if (!isRecord(catalogs)) throw new TypeError('i18n catalogs must be an object')
82
+ for (const language of Object.keys(catalogs)) assertLanguage(language)
83
+ const copy = {}
84
+ for (const language of SUPPORTED_LANGUAGES) {
85
+ if (catalogs[language] === undefined) continue
86
+ const localized = catalogs[language]
87
+ if (!isRecord(localized)) throw new TypeError(`i18n catalogs.${language} must be an object`)
88
+ copy[language] = Object.fromEntries(Object.entries(localized).map(([key, template]) => {
89
+ assertKey(key)
90
+ return [key, assertTemplate(template, key, language)]
91
+ }))
92
+ }
93
+ return copy
94
+ }
95
+
96
+ function mergeCatalogs(catalogs, overrides) {
97
+ const base = copyCatalogs(catalogs)
98
+ const extra = copyCatalogs(overrides)
99
+ const merged = {}
100
+ for (const language of SUPPORTED_LANGUAGES) {
101
+ if (base[language] || extra[language]) merged[language] = { ...base[language], ...extra[language] }
102
+ }
103
+ return merged
104
+ }
105
+
106
+ function freezeCatalogs(catalogs) {
107
+ for (const localized of Object.values(catalogs)) Object.freeze(localized)
108
+ return Object.freeze(catalogs)
109
+ }
110
+
111
+ function otherLanguage(language) {
112
+ return language === 'zh' ? 'en' : 'zh'
113
+ }
114
+
115
+ function resolutionChain(language, fallbackLanguage) {
116
+ const primary = normalizeLanguage(language)
117
+ if (fallbackLanguage === false || fallbackLanguage === null) return [primary]
118
+ const fallback = fallbackLanguage === undefined ? otherLanguage(primary) : normalizeLanguage(fallbackLanguage)
119
+ return primary === fallback ? [primary] : [primary, fallback]
120
+ }
121
+
122
+ export function createI18n(catalogs = {}, options = {}) {
123
+ if (!isRecord(options)) throw new TypeError('i18n options must be an object')
124
+ const frozen = freezeCatalogs(copyCatalogs(catalogs))
125
+ const language = normalizeLanguage(options.language)
126
+ const fallbackOption = options.fallbackLanguage
127
+ const fallbackLanguage = fallbackOption === false || fallbackOption === null
128
+ ? null
129
+ : normalizeLanguage(fallbackOption === undefined ? otherLanguage(language) : fallbackOption)
130
+
131
+ const api = {
132
+ language,
133
+ fallbackLanguage,
134
+ catalogs: frozen,
135
+
136
+ resolve(key, requestedLanguage = language) {
137
+ assertKey(key)
138
+ const chain = resolutionChain(requestedLanguage, fallbackOption)
139
+ for (const candidate of chain) {
140
+ const localized = frozen[candidate]
141
+ if (localized && Object.hasOwn(localized, key)) {
142
+ return Object.freeze({
143
+ key,
144
+ language: candidate,
145
+ fallback: candidate !== normalizeLanguage(requestedLanguage),
146
+ text: localized[key],
147
+ })
148
+ }
149
+ }
150
+ throw new TemplateNotFoundError(key, chain)
151
+ },
152
+
153
+ t(key, values = {}, requestedLanguage = language) {
154
+ const resolved = api.resolve(key, requestedLanguage)
155
+ return interpolate(resolved.text, values, { key, language: resolved.language })
156
+ },
157
+
158
+ withOverrides(overrides) {
159
+ return createI18n(mergeCatalogs(frozen, overrides), {
160
+ language,
161
+ fallbackLanguage: fallbackOption,
162
+ })
163
+ },
164
+ }
165
+ return Object.freeze(api)
166
+ }