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,326 @@
1
+ /**
2
+ * Outbox 房与宿主模块化状态事务之间的适配层。
3
+ *
4
+ * 宿主以 modularVersion 做整份模块化状态的 CAS;Outbox 房只看到自己的数组与
5
+ * revision。这里负责两种形状的互换、有限冲突重试,以及崩溃恢复后的发送闭环。
6
+ * 网络副作用只能由注入的 send(message) 完成。
7
+ */
8
+ import { randomUUID } from 'node:crypto'
9
+ import {
10
+ OutboxCasConflictError,
11
+ claim as claimOutbox,
12
+ createOutboxState,
13
+ enqueue as enqueueOutbox,
14
+ recover as recoverOutbox,
15
+ retry as retryOutbox,
16
+ settle as settleOutbox,
17
+ } from './outbox.js'
18
+
19
+ const DEFAULT_MAX_CAS_RETRIES = 4
20
+ const DEFAULT_FLUSH_LIMIT = 100
21
+
22
+ function isObject(value) {
23
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
24
+ }
25
+
26
+ function errorText(error, fallback = 'unknown error') {
27
+ return String(error && error.message || error || fallback).slice(0, 240)
28
+ }
29
+
30
+ function modularVersionOf(state) {
31
+ const version = state && state.modularVersion
32
+ return Number.isSafeInteger(version) && version >= 0 ? version : 0
33
+ }
34
+
35
+ function expectedVersionOf(state) {
36
+ if (state && Number.isSafeInteger(state.modularVersion) && state.modularVersion >= 0) {
37
+ return state.modularVersion
38
+ }
39
+ if (state && Number.isSafeInteger(state.revision) && state.revision >= 0) return state.revision
40
+ throw new TypeError('expected outbox state must contain a non-negative revision')
41
+ }
42
+
43
+ function outboxStateOf(root) {
44
+ if (root !== undefined && root !== null && !isObject(root)) {
45
+ throw new TypeError('modular state must be an object')
46
+ }
47
+ const source = root || {}
48
+ const revision = modularVersionOf(source)
49
+ if (source.outbox === undefined) return createOutboxState({ revision })
50
+ if (Array.isArray(source.outbox)) return createOutboxState({ outbox: source.outbox, revision })
51
+ if (isObject(source.outbox) && Array.isArray(source.outbox.outbox)) {
52
+ return createOutboxState({ ...source.outbox, revision })
53
+ }
54
+ throw new TypeError('modular state outbox must be an array or an outbox state')
55
+ }
56
+
57
+ function mergeOutboxState(disk, next) {
58
+ if (disk !== undefined && disk !== null && !isObject(disk)) {
59
+ throw new TypeError('modular state mutator requires an object')
60
+ }
61
+ const root = disk || {}
62
+ // 同时读取早期可能落盘的完整 Outbox 房形状;新写入默认只保存消息数组,
63
+ // revision 由宿主 modularVersion 统一提供,避免两个版本号各自漂移。
64
+ if (isObject(root.outbox) && Array.isArray(root.outbox.outbox)) {
65
+ return {
66
+ ...root,
67
+ outbox: {
68
+ ...root.outbox,
69
+ outboxVersion: next.outboxVersion,
70
+ revision: next.revision,
71
+ outbox: next.outbox,
72
+ },
73
+ }
74
+ }
75
+ return { ...root, outbox: next.outbox }
76
+ }
77
+
78
+ function hasCasConflictEvidence(value) {
79
+ if (!value) return false
80
+ if (typeof value === 'string') return /MODULAR_CAS_CONFLICT|OUTBOX_CAS_CONFLICT|CAS conflict/i.test(value)
81
+ if (!isObject(value)) return false
82
+ if (value.code === 'MODULAR_CAS_CONFLICT' || value.code === 'OUTBOX_CAS_CONFLICT') return true
83
+ return hasCasConflictEvidence(value.message)
84
+ || hasCasConflictEvidence(value.error)
85
+ || hasCasConflictEvidence(value.writeError)
86
+ }
87
+
88
+ function invalidCommitReceipt() {
89
+ return new TypeError('commitModularState must acknowledge true/{ok:true}/next state or reject false/{ok:false}/CAS conflict')
90
+ }
91
+
92
+ function commitReceipt(receipt, expectedVersion) {
93
+ if (receipt === true) return true
94
+ if (receipt === false) return false
95
+ if (!isObject(receipt)) throw invalidCommitReceipt()
96
+ if (receipt.ok === true) return true
97
+ if (receipt.ok === false) return false
98
+
99
+ // 现有 writeState 成功时直接返回 merged,CAS 失败时把异常写进 writeError。
100
+ // 显式 writeError 优先:冲突后的 actualVersion 可能恰好是 expected+1,不能误认成功。
101
+ // 其他写盘异常也不能伪装成可重试冲突。
102
+ if (hasCasConflictEvidence(receipt)) return false
103
+ if (receipt.writeError) {
104
+ const error = new Error(`modular outbox commit failed: ${errorText(receipt.writeError)}`)
105
+ error.code = 'OUTBOX_MODULAR_COMMIT_FAILED'
106
+ throw error
107
+ }
108
+ if (Number.isSafeInteger(receipt.modularVersion) && receipt.modularVersion === expectedVersion + 1) return true
109
+ if (Number.isSafeInteger(receipt.modularVersion)) return false
110
+ throw invalidCommitReceipt()
111
+ }
112
+
113
+ /** 把 commitModularState(expectedVersion, mutate) 适配成 Outbox 的 commit(next, expected)。 */
114
+ export function createModularOutboxCommit({ commitModularState } = {}) {
115
+ if (typeof commitModularState !== 'function') {
116
+ throw new TypeError('createModularOutboxCommit requires commitModularState')
117
+ }
118
+ return async function commit(next, expected) {
119
+ const expectedVersion = expectedVersionOf(expected)
120
+ let receipt
121
+ try {
122
+ receipt = await commitModularState(expectedVersion, (disk) => mergeOutboxState(disk, next))
123
+ } catch (error) {
124
+ if (hasCasConflictEvidence(error)) return false
125
+ throw error
126
+ }
127
+ return commitReceipt(receipt, expectedVersion)
128
+ }
129
+ }
130
+
131
+ function retryLimit(value) {
132
+ const limit = value === undefined ? DEFAULT_MAX_CAS_RETRIES : value
133
+ if (!Number.isSafeInteger(limit) || limit < 0) {
134
+ throw new TypeError('maxCasRetries must be a non-negative safe integer')
135
+ }
136
+ return limit
137
+ }
138
+
139
+ function flushLimit(value) {
140
+ const limit = value === undefined ? DEFAULT_FLUSH_LIMIT : value
141
+ if (!Number.isSafeInteger(limit) || limit < 0) {
142
+ throw new TypeError('flush limit must be a non-negative safe integer')
143
+ }
144
+ return limit
145
+ }
146
+
147
+ function sendSucceeded(receipt) {
148
+ if (receipt === true) return true
149
+ if (!isObject(receipt) || receipt.ok === false) return false
150
+ return receipt.ok === true || receipt.alreadySent === true
151
+ }
152
+
153
+ /**
154
+ * 单进程内串行 flush;首次 flush 自动 recover,显式 recover:true 可强制恢复。
155
+ * CAS 重试只包住状态迁移,绝不把已成功的外发包含进重试块而盲目再发一次。
156
+ */
157
+ export function createModularOutboxHost(options = {}) {
158
+ const { readState, commitModularState, send } = options
159
+ if (typeof readState !== 'function') throw new TypeError('createModularOutboxHost requires readState')
160
+ if (typeof send !== 'function') throw new TypeError('createModularOutboxHost requires send')
161
+ const commit = createModularOutboxCommit({ commitModularState })
162
+ const defaultCasRetries = retryLimit(options.maxCasRetries)
163
+ const ownerId = options.ownerId || randomUUID()
164
+ const leaseMs = options.leaseMs === undefined ? 60_000 : Number(options.leaseMs)
165
+ let recovered = false
166
+ let activeFlush = null
167
+
168
+ async function transact(operation, overrides = {}) {
169
+ const maxRetries = retryLimit(overrides.maxCasRetries === undefined ? defaultCasRetries : overrides.maxCasRetries)
170
+ let lastConflict = null
171
+ for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
172
+ const state = outboxStateOf(await readState())
173
+ try {
174
+ return await operation(state, commit)
175
+ } catch (error) {
176
+ if (!error || error.code !== 'OUTBOX_CAS_CONFLICT') throw error
177
+ lastConflict = error
178
+ }
179
+ }
180
+ throw lastConflict || new OutboxCasConflictError(createOutboxState(), createOutboxState({ revision: 1 }))
181
+ }
182
+
183
+ async function read() {
184
+ return outboxStateOf(await readState())
185
+ }
186
+
187
+ async function enqueue(message, overrides = {}) {
188
+ return transact((state, roomCommit) => enqueueOutbox({
189
+ state, message, commit: roomCommit, at: overrides.at,
190
+ }), overrides)
191
+ }
192
+
193
+ async function recover(overrides = {}) {
194
+ const result = await transact((state, roomCommit) => recoverOutbox({
195
+ state, commit: roomCommit, at: overrides.at,
196
+ }), overrides)
197
+ recovered = true
198
+ return result
199
+ }
200
+
201
+ function summarize({ state, queueStatus, nextAt, recovery, results, limited = false }) {
202
+ const sent = results.filter((result) => result.status === 'sent').length
203
+ const failed = results.filter((result) => result.status === 'failed').length
204
+ const stale = results.filter((result) => result.status === 'stale').length
205
+ const alreadySent = results.filter((result) => result.status === 'sent' && result.alreadySent).length
206
+ let status = queueStatus
207
+ if (limited) status = 'limited'
208
+ else if (results.length) status = failed ? 'failed' : sent ? 'sent' : 'stale'
209
+ return {
210
+ status,
211
+ queueStatus,
212
+ state,
213
+ recovery,
214
+ recoveredIds: recovery ? [...recovery.recoveredIds] : [],
215
+ results,
216
+ sent,
217
+ failed,
218
+ stale,
219
+ alreadySent,
220
+ nextAt,
221
+ }
222
+ }
223
+
224
+ async function runFlush(overrides) {
225
+ const at = overrides.at
226
+ const limit = flushLimit(overrides.limit === undefined ? overrides.maxMessages : overrides.limit)
227
+ const retryOptions = { maxCasRetries: overrides.maxCasRetries }
228
+ let recovery = null
229
+ if (overrides.recover === true || (overrides.recover !== false && !recovered)) {
230
+ recovery = await recover({ at, maxCasRetries: overrides.maxCasRetries })
231
+ }
232
+
233
+ const results = []
234
+ for (let index = 0; index < limit; index += 1) {
235
+ const claimed = await transact((state, roomCommit) => claimOutbox({
236
+ state, commit: roomCommit, ticketId: overrides.ticketId, at,
237
+ ownerId, leaseMs: overrides.leaseMs === undefined ? leaseMs : overrides.leaseMs,
238
+ }), retryOptions)
239
+ if (claimed.status !== 'claimed') {
240
+ return summarize({
241
+ state: claimed.state,
242
+ queueStatus: claimed.status,
243
+ nextAt: claimed.nextAt,
244
+ recovery,
245
+ results,
246
+ })
247
+ }
248
+
249
+ const message = claimed.message
250
+ const base = { id: message.id, ticketId: message.ticketId, attempts: message.attempts }
251
+ let receipt = null
252
+ let failure = null
253
+ try {
254
+ receipt = await send(message)
255
+ if (!sendSucceeded(receipt)) failure = errorText(receipt && receipt.error, 'send was not acknowledged')
256
+ } catch (error) {
257
+ failure = errorText(error)
258
+ }
259
+
260
+ if (failure === null) {
261
+ const settled = await transact((state, roomCommit) => settleOutbox({
262
+ state,
263
+ id: message.id,
264
+ result: 'sent',
265
+ attempts: message.attempts,
266
+ commit: roomCommit,
267
+ at,
268
+ }), retryOptions)
269
+ results.push({
270
+ ...base,
271
+ status: settled.status === 'stale' ? 'stale' : 'sent',
272
+ alreadySent: isObject(receipt) && receipt.alreadySent === true,
273
+ receipt,
274
+ })
275
+ } else {
276
+ const retried = await transact((state, roomCommit) => retryOutbox({
277
+ state,
278
+ id: message.id,
279
+ attempts: message.attempts,
280
+ commit: roomCommit,
281
+ at,
282
+ baseDelayMs: overrides.baseDelayMs === undefined ? options.baseDelayMs : overrides.baseDelayMs,
283
+ maxDelayMs: overrides.maxDelayMs === undefined ? options.maxDelayMs : overrides.maxDelayMs,
284
+ error: failure,
285
+ }), retryOptions)
286
+ results.push({
287
+ ...base,
288
+ status: retried.status === 'stale' ? 'stale' : 'failed',
289
+ alreadySent: false,
290
+ receipt,
291
+ error: failure,
292
+ })
293
+ }
294
+ }
295
+
296
+ return summarize({
297
+ state: await read(),
298
+ queueStatus: null,
299
+ nextAt: null,
300
+ recovery,
301
+ results,
302
+ limited: true,
303
+ })
304
+ }
305
+
306
+ function flush(overrides = {}) {
307
+ const scope = overrides.ticketId === undefined ? '*' : String(overrides.ticketId)
308
+ if (activeFlush) {
309
+ if (activeFlush.scope === scope) return activeFlush.promise
310
+ // 不同 scope 不能共享 A 的回执:等当前 recover/send 结束后,再跑自己的 flush。
311
+ return activeFlush.promise.then(() => flush(overrides), () => flush(overrides))
312
+ }
313
+ const active = { scope, promise: null }
314
+ active.promise = (async () => {
315
+ try {
316
+ return await runFlush(overrides)
317
+ } finally {
318
+ if (activeFlush === active) activeFlush = null
319
+ }
320
+ })()
321
+ activeFlush = active
322
+ return active.promise
323
+ }
324
+
325
+ return Object.freeze({ read, enqueue, recover, flush })
326
+ }
@@ -0,0 +1,222 @@
1
+ /** 单用户模块化运行时:组合 Ticket/订阅/Assignment/Admission,不直接写宿主或 Outbox。 */
2
+ import { create as createTicket, resume as resumeTicket, end as endTicket } from './ticket-state.js'
3
+ import { createThreadSubscriptionState, subscribe, unsubscribe, syncTicketState, routeThreadEvent } from './thread-subscription.js'
4
+ import { planAssignment, startAssignment, promptAssignment, stopAssignment, transitionAssignment } from './execution-assignment.js'
5
+ import { workerSessionId } from './executor-host.js'
6
+ import { evaluateAdmission } from './admission-eval.js'
7
+ import { projectRecords, projectExecution, projectDeployment } from './ticket-projection.js'
8
+ import { createPromptConfig } from './prompt-config.js'
9
+ import { createI18n, normalizeLanguage } from './i18n.js'
10
+
11
+ function isObject(value) {
12
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
13
+ }
14
+
15
+ function required(value, name) {
16
+ const text = String(value ?? '').trim()
17
+ if (!text) throw new TypeError(`${name} is required`)
18
+ return text
19
+ }
20
+
21
+ export function runtimeThreadKey({ provider = 'github', repo, number } = {}) {
22
+ return `${provider}:${required(repo, 'repo')}#${required(number, 'number')}`
23
+ }
24
+
25
+ export function runtimeTicketId(threadKey) {
26
+ return `ticket:${required(threadKey, 'threadKey')}`
27
+ }
28
+
29
+ export function createModularRuntimeState(fields = {}) {
30
+ const source = isObject(fields) ? fields : {}
31
+ return {
32
+ ...source,
33
+ tickets: isObject(source.tickets) ? { ...source.tickets } : {},
34
+ subscriptions: createThreadSubscriptionState(source.subscriptions),
35
+ assignments: isObject(source.assignments) ? { ...source.assignments } : {},
36
+ promptConfig: createPromptConfig(source.promptConfig),
37
+ locale: normalizeLanguage(source.locale),
38
+ }
39
+ }
40
+
41
+ function latestAssignment(state, ticket) {
42
+ if (ticket.assignmentId && state.assignments[ticket.assignmentId]) return state.assignments[ticket.assignmentId]
43
+ const rows = Object.values(state.assignments).filter((row) => row.ticketId === ticket.id)
44
+ return rows.filter((row) => row.status !== 'ended').at(-1) || rows.at(-1) || null
45
+ }
46
+
47
+ function commitTicketView(state, { ticket, assignment, subscriptions }) {
48
+ return {
49
+ ...state,
50
+ tickets: { ...state.tickets, [ticket.id]: ticket },
51
+ assignments: { ...state.assignments, [assignment.id]: assignment },
52
+ subscriptions,
53
+ }
54
+ }
55
+
56
+ /** 创建或复用 Ticket 与 Assignment;纯规划,不启动 Executor。 */
57
+ export function ensureTicket(input, spec = {}) {
58
+ const state = createModularRuntimeState(input)
59
+ const mode = spec.mode === 'worker' ? 'worker' : 'inline'
60
+ const threadKey = spec.threadKey || runtimeThreadKey(spec)
61
+ const ticketId = runtimeTicketId(threadKey)
62
+ const previous = state.tickets[ticketId] || null
63
+ if (previous && previous.status === 'ended') {
64
+ return { state, ticket: previous, assignment: latestAssignment(state, previous), action: 'ended', mode }
65
+ }
66
+ const created = previous || createTicket({ id: ticketId, threadKey, at: spec.at, eventId: spec.eventId ? `${spec.eventId}:create` : undefined, detail: spec.detail })
67
+ const sessionId = mode === 'worker' ? workerSessionId(ticketId) : required(spec.sessionId, 'sessionId')
68
+ const workdir = spec.workdir || previous && previous.workdir
69
+ const planned = planAssignment({
70
+ ticket: created,
71
+ assignment: latestAssignment(state, created),
72
+ sessionId, workdir,
73
+ retry: spec.retry === true,
74
+ at: spec.at, eventId: spec.eventId ? `${spec.eventId}:assign` : undefined, detail: spec.detail,
75
+ })
76
+ let subscriptions = state.subscriptions
77
+ const active = subscriptions.subscriptions[threadKey]
78
+ if (active && active.active === true
79
+ && (active.ticketId !== ticketId || active.sessionId !== planned.assignment.sessionId)) {
80
+ subscriptions = unsubscribe(subscriptions, threadKey)
81
+ }
82
+ subscriptions = subscribe(subscriptions, {
83
+ threadKey, ticketId, sessionId: planned.assignment.sessionId,
84
+ ticketStatus: planned.ticket.status, endReason: planned.ticket.endReason,
85
+ at: spec.at,
86
+ })
87
+ subscriptions = syncTicketState(subscriptions, threadKey, {
88
+ status: planned.ticket.status, endReason: planned.ticket.endReason,
89
+ })
90
+ return {
91
+ state: commitTicketView(state, { ...planned, subscriptions }),
92
+ ticket: planned.ticket,
93
+ assignment: planned.assignment,
94
+ action: previous ? planned.action : 'start',
95
+ mode,
96
+ }
97
+ }
98
+
99
+ /** 只有显式 worker 才会触达 Executor;inline 调用直接拒绝,避免无意换执行体。 */
100
+ export async function startRuntimeAssignment(input, { ticketId, executor, prompt, messageId } = {}) {
101
+ const state = createModularRuntimeState(input)
102
+ const ticket = state.tickets[required(ticketId, 'ticketId')]
103
+ if (!ticket) throw new Error(`ticket not found: ${ticketId}`)
104
+ const assignment = latestAssignment(state, ticket)
105
+ if (!assignment) throw new Error(`assignment not found: ${ticketId}`)
106
+ if (assignment.sessionId !== workerSessionId(ticket.id)) throw new Error('startRuntimeAssignment requires an explicit worker assignment')
107
+ const started = await startAssignment({ executor, ticket, assignment })
108
+ const prompted = prompt === undefined ? null : await promptAssignment({ executor, ticket, assignment, prompt, messageId })
109
+ return { state, ticket, assignment, receipt: started.receipt, promptReceipt: prompted && prompted.receipt }
110
+ }
111
+
112
+ /** 路由后续事件;worker 的外部副作用由显式 executor 执行,返回值仍包含完整新状态。 */
113
+ export async function routeRuntimeEvent(input, event = {}, options = {}) {
114
+ const state = createModularRuntimeState(input)
115
+ const mode = options.mode === 'worker' ? 'worker' : 'inline'
116
+ const routed = routeThreadEvent(state.subscriptions, event)
117
+ let next = { ...state, subscriptions: routed.state }
118
+ let ticket = routed.ticketId
119
+ ? next.tickets[routed.ticketId] || null
120
+ : next.tickets[runtimeTicketId(routed.threadKey)] || null
121
+ let assignment = ticket ? latestAssignment(next, ticket) : null
122
+
123
+ if (routed.disposition === 'deliver' && ticket && assignment && assignment.status !== 'ended') {
124
+ const currentMode = String(assignment.sessionId).startsWith('worker-') ? 'worker' : 'inline'
125
+ if (currentMode !== mode) {
126
+ let previous = assignment
127
+ if (currentMode === 'worker') {
128
+ if (!options.executor) throw new Error('worker-to-inline requires executor to stop the old worker')
129
+ previous = (await stopAssignment({ executor: options.executor, ticket, assignment, reason: 'execution-mode-changed' })).assignment
130
+ } else {
131
+ previous = transitionAssignment(assignment, 'ended')
132
+ }
133
+ next = { ...next, assignments: { ...next.assignments, [previous.id]: previous } }
134
+ const replanned = ensureTicket(next, {
135
+ threadKey: ticket.threadKey,
136
+ sessionId: options.sessionId || ticket.ownerSessionId,
137
+ workdir: options.workdir || ticket.workdir,
138
+ mode, at: event.at, eventId: routed.eventId,
139
+ })
140
+ next = replanned.state
141
+ ticket = replanned.ticket
142
+ assignment = replanned.assignment
143
+ }
144
+ }
145
+
146
+ if (routed.disposition === 'resume' && ticket) {
147
+ const resumed = resumeTicket(ticket, {
148
+ actor: 'human', at: event.at, eventId: routed.eventId ? `${routed.eventId}:resume` : undefined, detail: event.body || event.detail,
149
+ })
150
+ // 先显式写入 resumed,再规划下一派工,不能让旧 ended Ticket 被普通评论直接 assign。
151
+ next = { ...next, tickets: { ...next.tickets, [ticket.id]: resumed } }
152
+ const replanned = ensureTicket(next, {
153
+ threadKey: ticket.threadKey,
154
+ sessionId: options.sessionId || ticket.ownerSessionId,
155
+ workdir: options.workdir || ticket.workdir,
156
+ mode, at: event.at, eventId: routed.eventId,
157
+ })
158
+ next = replanned.state
159
+ ticket = replanned.ticket
160
+ assignment = replanned.assignment
161
+ }
162
+
163
+ if (mode === 'worker' && !options.deferExecution && (routed.disposition === 'deliver' || routed.disposition === 'resume') && ticket && assignment) {
164
+ await startRuntimeAssignment(next, {
165
+ ticketId: ticket.id,
166
+ executor: options.executor,
167
+ prompt: event.body || event.detail || 'continue',
168
+ messageId: routed.eventId,
169
+ })
170
+ }
171
+ return { state: next, ticket, assignment, disposition: routed.disposition, reason: routed.reason }
172
+ }
173
+
174
+ /** 完成 Ticket;worker 可显式停止宿主执行体,inline 只写状态。 */
175
+ export async function completeRuntimeTicket(input, ticketId, options = {}) {
176
+ const state = createModularRuntimeState(input)
177
+ const ticket = state.tickets[required(ticketId, 'ticketId')]
178
+ if (!ticket) throw new Error(`ticket not found: ${ticketId}`)
179
+ const assignment = latestAssignment(state, ticket)
180
+ const reason = options.reason || 'completed'
181
+ let nextAssignment = assignment
182
+ if (assignment && assignment.status !== 'ended') {
183
+ nextAssignment = options.mode === 'worker'
184
+ ? (await stopAssignment({ executor: options.executor, ticket, assignment, reason })).assignment
185
+ : transitionAssignment(assignment, 'ended')
186
+ }
187
+ const ended = endTicket(ticket, {
188
+ at: options.at, eventId: options.eventId, reason, detail: options.detail,
189
+ })
190
+ const subscriptions = syncTicketState(state.subscriptions, ticket.threadKey, { status: 'ended', endReason: reason })
191
+ return {
192
+ state: {
193
+ ...state,
194
+ tickets: { ...state.tickets, [ticket.id]: ended },
195
+ assignments: nextAssignment ? { ...state.assignments, [nextAssignment.id]: nextAssignment } : state.assignments,
196
+ subscriptions,
197
+ },
198
+ ticket: ended,
199
+ assignment: nextAssignment,
200
+ }
201
+ }
202
+
203
+ export function projectRuntime(input, healthOptions = {}) {
204
+ const state = createModularRuntimeState(input)
205
+ const subscriptions = state.subscriptions.subscriptions
206
+ const outbox = state.outbox && Array.isArray(state.outbox.outbox) ? state.outbox.outbox : state.outbox
207
+ return {
208
+ records: projectRecords({ tickets: state.tickets, subscriptions, assignments: state.assignments, outbox }),
209
+ execution: projectExecution({ tickets: state.tickets, subscriptions, assignments: state.assignments, outbox, ...healthOptions, paused: state.executorPaused === true || healthOptions.paused }),
210
+ deployment: projectDeployment(healthOptions),
211
+ draft: state.draft || null,
212
+ actions: true,
213
+ locale: state.locale,
214
+ }
215
+ }
216
+
217
+ export function renderRuntimePrompt(key, values, options = {}) {
218
+ const config = createPromptConfig(options.promptConfig)
219
+ return createI18n(config, { language: options.locale }).t(key, values)
220
+ }
221
+
222
+ export { evaluateAdmission }