66 lines
1.8 KiB
TypeScript
66 lines
1.8 KiB
TypeScript
export interface PascalAgentJob {
|
|
controller: AbortController
|
|
conversationId: string
|
|
ownerId: string
|
|
sceneId: string
|
|
startedAt: number
|
|
}
|
|
|
|
type PascalAgentJobRegistry = Map<string, PascalAgentJob>
|
|
|
|
const globalForPascalAgentJobs = globalThis as typeof globalThis & {
|
|
__pascalAgentJobs?: PascalAgentJobRegistry
|
|
}
|
|
|
|
if (!globalForPascalAgentJobs.__pascalAgentJobs) {
|
|
globalForPascalAgentJobs.__pascalAgentJobs = new Map<string, PascalAgentJob>()
|
|
}
|
|
const jobs = globalForPascalAgentJobs.__pascalAgentJobs
|
|
|
|
function jobKey(ownerId: string, conversationId: string): string {
|
|
return `${ownerId}:${conversationId}`
|
|
}
|
|
|
|
export function startPascalAgentJob(input: {
|
|
conversationId: string
|
|
ownerId: string
|
|
sceneId: string
|
|
}): PascalAgentJob | null {
|
|
const key = jobKey(input.ownerId, input.conversationId)
|
|
if (jobs.has(key)) return null
|
|
|
|
const job: PascalAgentJob = {
|
|
...input,
|
|
controller: new AbortController(),
|
|
startedAt: Date.now(),
|
|
}
|
|
jobs.set(key, job)
|
|
return job
|
|
}
|
|
|
|
export function isPascalAgentJobActive(input: {
|
|
conversationId: string
|
|
ownerId: string
|
|
sceneId: string
|
|
}): boolean {
|
|
const job = jobs.get(jobKey(input.ownerId, input.conversationId))
|
|
return Boolean(job && job.sceneId === input.sceneId && !job.controller.signal.aborted)
|
|
}
|
|
|
|
export function cancelPascalAgentJob(input: {
|
|
conversationId: string
|
|
ownerId: string
|
|
sceneId: string
|
|
}): boolean {
|
|
const job = jobs.get(jobKey(input.ownerId, input.conversationId))
|
|
if (!job || job.sceneId !== input.sceneId) return false
|
|
job.controller.abort(new Error('Pascal agent job cancelled by user'))
|
|
return true
|
|
}
|
|
|
|
export function finishPascalAgentJob(job: PascalAgentJob | null): void {
|
|
if (!job) return
|
|
const key = jobKey(job.ownerId, job.conversationId)
|
|
if (jobs.get(key) === job) jobs.delete(key)
|
|
}
|