@unieai/rabi-api-session-controller 0.0.0-stage → 0.2.2-rc.5
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.
- package/LICENSE +21 -0
- package/README.md +7 -2
- package/lib/client.js +4 -0
- package/lib/index.js +4300 -0
- package/lib/typert.host.d.ts +3 -0
- package/lib/typert.host.js +5013 -0
- package/lib/typert.remote-client.d.ts +115 -0
- package/lib/typert.remote-client.js +2714 -0
- package/lib/types/agent.d.ts +164 -0
- package/lib/types/agent.js +484 -0
- package/lib/types/archived-session-gate.d.ts +33 -0
- package/lib/types/archived-session-gate.js +54 -0
- package/lib/types/assistant-stream.d.ts +26 -0
- package/lib/types/assistant-stream.js +82 -0
- package/lib/types/catalog.d.ts +24 -0
- package/lib/types/catalog.js +107 -0
- package/lib/types/client/contract/events.d.ts +102 -0
- package/lib/types/client/contract/events.js +111 -0
- package/lib/types/client/contract/session.d.ts +178 -0
- package/lib/types/client/contract/session.js +1 -0
- package/lib/types/client/contract/sessions.d.ts +162 -0
- package/lib/types/client/contract/sessions.js +1 -0
- package/lib/types/client/contract/snapshot.d.ts +84 -0
- package/lib/types/client/contract/snapshot.js +1 -0
- package/lib/types/client/index.d.ts +39 -0
- package/lib/types/client/index.js +60 -0
- package/lib/types/client/ordered-baseline.d.ts +12 -0
- package/lib/types/client/ordered-baseline.js +40 -0
- package/lib/types/client/scope.d.ts +46 -0
- package/lib/types/client/scope.js +46 -0
- package/lib/types/client/session-wire-event.d.ts +11 -0
- package/lib/types/client/session-wire-event.js +42 -0
- package/lib/types/client/sessions/assistant-stream.d.ts +56 -0
- package/lib/types/client/sessions/assistant-stream.js +182 -0
- package/lib/types/client/sessions/history-records.d.ts +22 -0
- package/lib/types/client/sessions/history-records.js +25 -0
- package/lib/types/client/sessions/lineage.d.ts +48 -0
- package/lib/types/client/sessions/lineage.js +55 -0
- package/lib/types/client/sessions/manager.d.ts +272 -0
- package/lib/types/client/sessions/manager.js +774 -0
- package/lib/types/client/sessions/notifier.d.ts +39 -0
- package/lib/types/client/sessions/notifier.js +97 -0
- package/lib/types/client/sessions/projection-store.d.ts +128 -0
- package/lib/types/client/sessions/projection-store.js +161 -0
- package/lib/types/client/sessions/remotes.d.ts +29 -0
- package/lib/types/client/sessions/remotes.js +7 -0
- package/lib/types/client/sessions/service.d.ts +263 -0
- package/lib/types/client/sessions/service.js +597 -0
- package/lib/types/client/sessions/session.d.ts +303 -0
- package/lib/types/client/sessions/session.js +991 -0
- package/lib/types/client/time-zone.d.ts +8 -0
- package/lib/types/client/time-zone.js +13 -0
- package/lib/types/client/transport.d.ts +77 -0
- package/lib/types/client/transport.js +130 -0
- package/lib/types/commands.d.ts +92 -0
- package/lib/types/commands.js +575 -0
- package/lib/types/continuation.d.ts +35 -0
- package/lib/types/continuation.js +47 -0
- package/lib/types/control.d.ts +20 -0
- package/lib/types/control.js +106 -0
- package/lib/types/file-references.d.ts +27 -0
- package/lib/types/file-references.js +68 -0
- package/lib/types/history/assistant-stream.d.ts +43 -0
- package/lib/types/history/assistant-stream.js +79 -0
- package/lib/types/history/controller.d.ts +104 -0
- package/lib/types/history/controller.js +293 -0
- package/lib/types/history/listener.d.ts +105 -0
- package/lib/types/history/listener.js +296 -0
- package/lib/types/history.d.ts +58 -0
- package/lib/types/history.js +152 -0
- package/lib/types/index.d.ts +262 -0
- package/lib/types/index.js +693 -0
- package/lib/types/list.d.ts +62 -0
- package/lib/types/list.js +343 -0
- package/lib/types/media-references.d.ts +18 -0
- package/lib/types/media-references.js +84 -0
- package/lib/types/remote-events.d.ts +8 -0
- package/lib/types/remote-events.js +1 -0
- package/lib/types/skill-catalog.d.ts +28 -0
- package/lib/types/skill-catalog.js +203 -0
- package/lib/types/state/controller.d.ts +45 -0
- package/lib/types/state/controller.js +288 -0
- package/lib/types/state/listener.d.ts +40 -0
- package/lib/types/state/listener.js +111 -0
- package/lib/types/types.d.ts +687 -0
- package/lib/types/types.js +5 -0
- package/lib/types/web/controller.d.ts +25 -0
- package/lib/types/web/controller.js +138 -0
- package/locale/de.json +6 -0
- package/locale/en.json +5 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +119 -4
- package/src/agent.ts +474 -0
- package/src/archived-session-gate.ts +59 -0
- package/src/assistant-stream.ts +102 -0
- package/src/catalog.ts +117 -0
- package/src/client/contract/events.ts +205 -0
- package/src/client/contract/session.ts +174 -0
- package/src/client/contract/sessions.ts +169 -0
- package/src/client/contract/snapshot.ts +94 -0
- package/src/client/index.ts +149 -0
- package/src/client/ordered-baseline.ts +43 -0
- package/src/client/scope.ts +76 -0
- package/src/client/session-wire-event.ts +46 -0
- package/src/client/sessions/assistant-stream.ts +229 -0
- package/src/client/sessions/history-records.ts +35 -0
- package/src/client/sessions/lineage.ts +96 -0
- package/src/client/sessions/manager.ts +857 -0
- package/src/client/sessions/notifier.ts +97 -0
- package/src/client/sessions/projection-store.ts +244 -0
- package/src/client/sessions/remotes.ts +44 -0
- package/src/client/sessions/service.ts +741 -0
- package/src/client/sessions/session.ts +1055 -0
- package/src/client/time-zone.ts +14 -0
- package/src/client/transport.ts +247 -0
- package/src/commands.ts +602 -0
- package/src/continuation.ts +58 -0
- package/src/control.ts +121 -0
- package/src/file-references.ts +42 -0
- package/src/history/assistant-stream.ts +102 -0
- package/src/history/controller.ts +256 -0
- package/src/history/listener.ts +302 -0
- package/src/history.ts +189 -0
- package/src/index.ts +651 -0
- package/src/list.ts +382 -0
- package/src/media-references.ts +84 -0
- package/src/remote-events.ts +14 -0
- package/src/skill-catalog.ts +108 -0
- package/src/state/controller.ts +221 -0
- package/src/state/listener.ts +116 -0
- package/src/types.ts +720 -0
- package/src/web/controller.ts +78 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/** Passive Session state, coalesced observations and quiescence waits. */
|
|
2
|
+
|
|
3
|
+
import type { Context } from '@unieai/cordis'
|
|
4
|
+
import type { Agent } from '@unieai/rabi-agent'
|
|
5
|
+
import type {} from '@unieai/rabi-api-gateway'
|
|
6
|
+
import type { UserMessage } from '@unieai/rabi-llm'
|
|
7
|
+
import type { SessionId } from '@unieai/rabi-session'
|
|
8
|
+
import { deadline, MAX_TIMER_DELAY_MS, timeoutOf } from '@unieai/rabi-timeout'
|
|
9
|
+
import { RemoteError } from '@unieai/rabi-typert-protocol'
|
|
10
|
+
import type { JsonValue } from '@unieai/rabi-util-values'
|
|
11
|
+
import type { HistoryController } from '../history/controller.ts'
|
|
12
|
+
import { DEFAULT_MAX_MESSAGES, rejectNotFound } from '../history.ts'
|
|
13
|
+
import type { SessionPendingInput, SessionQueuedItem, SessionState, SessionStateRequest, SessionWaitRequest, SessionWaitValue } from '../types.ts'
|
|
14
|
+
|
|
15
|
+
import { StateListener } from './listener.ts'
|
|
16
|
+
import type { VersionedSessionState } from './listener.ts'
|
|
17
|
+
|
|
18
|
+
const DEFAULT_WAIT_TIMEOUT_MS = 30_000
|
|
19
|
+
|
|
20
|
+
/** Reads and waits without activating or cancelling Session execution. */
|
|
21
|
+
export class StateController {
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param ctx - live Session and pending Remote event services.
|
|
25
|
+
* @param historyController - passive read entry used for cold state and its bounded output.
|
|
26
|
+
*/
|
|
27
|
+
constructor(private readonly ctx: Context, private readonly historyController: HistoryController) {}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Read passive execution and pending-input state.
|
|
31
|
+
* @param request - Session identity.
|
|
32
|
+
* @param signal - read cancellation.
|
|
33
|
+
* @returns current passive state.
|
|
34
|
+
*/
|
|
35
|
+
async state(request: SessionStateRequest, signal: AbortSignal): Promise<SessionState> {
|
|
36
|
+
return this.readState(request.sessionId, signal)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Observe complete passive state replacements.
|
|
41
|
+
* @param request - Session identity.
|
|
42
|
+
* @param signal - observation cancellation.
|
|
43
|
+
* @returns complete state replacements, starting with the current state.
|
|
44
|
+
*/
|
|
45
|
+
async *observeState(request: SessionStateRequest, signal: AbortSignal): AsyncIterable<SessionState> {
|
|
46
|
+
using listener = this.listen(request.sessionId, signal)
|
|
47
|
+
for await (const { state } of listener.observeStates()) yield state
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Wait for quiescence, pending input, or the deadline without cancelling execution.
|
|
52
|
+
* @param request - Session identity, timeout and assistant output window.
|
|
53
|
+
* @param signal - cancellation of this wait only, never of Agent execution.
|
|
54
|
+
* @returns the stopping reason and last complete state; no state before timeout is an error.
|
|
55
|
+
*/
|
|
56
|
+
async wait(request: SessionWaitRequest, signal: AbortSignal): Promise<SessionWaitValue> {
|
|
57
|
+
const timeoutMs = request.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS
|
|
58
|
+
const afterSeq = request.afterSeq ?? -1
|
|
59
|
+
const maxMessages = request.maxMessages ?? DEFAULT_MAX_MESSAGES
|
|
60
|
+
if (!Number.isSafeInteger(afterSeq) || afterSeq < -1 || Object.is(afterSeq, -0)) {
|
|
61
|
+
throw new RemoteError('gateway/bad-request', 'afterSeq must be an integer greater than or equal to -1', {})
|
|
62
|
+
}
|
|
63
|
+
if (!Number.isSafeInteger(maxMessages) || maxMessages <= 0) {
|
|
64
|
+
throw new RemoteError('gateway/bad-request', 'maxMessages must be a positive safe integer', {})
|
|
65
|
+
}
|
|
66
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_DELAY_MS) {
|
|
67
|
+
throw new RemoteError('gateway/bad-request', 'timeoutMs must be a positive supported timer delay', {})
|
|
68
|
+
}
|
|
69
|
+
using timer = deadline(signal, timeoutMs, 'session/wait-timeout')
|
|
70
|
+
using listener = this.listen(request.sessionId, timer.signal)
|
|
71
|
+
const sessionId = request.sessionId
|
|
72
|
+
const statesGenerator = listener.observeStates(1_000)
|
|
73
|
+
let nextStatePromise = statesGenerator.next()
|
|
74
|
+
let currentState: SessionState | undefined
|
|
75
|
+
let reason: SessionWaitValue['reason'] = 'timeout'
|
|
76
|
+
try {
|
|
77
|
+
for (;;) {
|
|
78
|
+
const observedState = await nextStatePromise
|
|
79
|
+
if (observedState.done) {
|
|
80
|
+
timer.signal.throwIfAborted()
|
|
81
|
+
throw new RemoteError('session/observation-ended', 'Session observation ended before a stopping state', {})
|
|
82
|
+
}
|
|
83
|
+
nextStatePromise = statesGenerator.next()
|
|
84
|
+
// Observe rejection on immediate exits without replacing the original demand.
|
|
85
|
+
void nextStatePromise.catch(() => undefined)
|
|
86
|
+
// Only a state the listener still confirms may drive this wait; an invalidated
|
|
87
|
+
// sample never becomes the state a timeout reports.
|
|
88
|
+
if (!listener.isCurrent(observedState.value.revision)) continue
|
|
89
|
+
currentState = observedState.value.state
|
|
90
|
+
const action = computeWaitAction(currentState)
|
|
91
|
+
if (action === 'continue') continue
|
|
92
|
+
if (action === 'input-required' || action === 'idle') {
|
|
93
|
+
reason = action
|
|
94
|
+
break
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const agent = this.ctx.agents.get(sessionId)
|
|
98
|
+
if (agent === undefined || this.ctx.sessions.get(sessionId) !== agent.session) continue
|
|
99
|
+
if (await waitForIdleOrStateChange(agent, nextStatePromise) === 'state-changed') continue
|
|
100
|
+
if (!listener.isCurrent(observedState.value.revision) || this.ctx.agents.get(sessionId) !== agent
|
|
101
|
+
|| this.ctx.sessions.get(sessionId) !== agent.session) continue
|
|
102
|
+
reason = 'idle'
|
|
103
|
+
break
|
|
104
|
+
}
|
|
105
|
+
} catch (error: unknown) {
|
|
106
|
+
// A caller cancellation is never a wait outcome; the deadline absorbs only the read
|
|
107
|
+
// it cancelled, and any other failure keeps its own error.
|
|
108
|
+
if (signal.aborted) throw signal.reason
|
|
109
|
+
if (!expired(timer.signal, error)) throw error
|
|
110
|
+
} finally {
|
|
111
|
+
// Wake/cancel a pending read before asking the generator to return.
|
|
112
|
+
listener[Symbol.dispose]()
|
|
113
|
+
await nextStatePromise.catch(() => undefined)
|
|
114
|
+
await statesGenerator.return(undefined)
|
|
115
|
+
}
|
|
116
|
+
signal.throwIfAborted()
|
|
117
|
+
if (currentState === undefined) throw new RemoteError('session/wait-timeout', 'No Session state arrived before the wait deadline', {})
|
|
118
|
+
const output = await this.historyController.assistantOutput(
|
|
119
|
+
sessionId, afterSeq, currentState.cursor, maxMessages, signal,
|
|
120
|
+
)
|
|
121
|
+
return { reason, state: currentState, output }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private listen(sessionId: SessionId, signal: AbortSignal): StateListener {
|
|
125
|
+
return new StateListener(this.ctx, sessionId, signal, readSignal => this.readState(sessionId, readSignal))
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* @param sessionId - Session to sample.
|
|
130
|
+
* @param signal - read cancellation.
|
|
131
|
+
* @param retried - whether a live source already redirected this read once.
|
|
132
|
+
* @returns one passive state sample.
|
|
133
|
+
*/
|
|
134
|
+
private async readState(sessionId: SessionId, signal: AbortSignal, retried = false): Promise<SessionState> {
|
|
135
|
+
signal.throwIfAborted()
|
|
136
|
+
const agent = this.ctx.agents.get(sessionId)
|
|
137
|
+
if (agent !== undefined) {
|
|
138
|
+
if (agent.session.header.cwd === undefined) rejectNotFound({ kind: 'session', sessionId })
|
|
139
|
+
return {
|
|
140
|
+
cursor: agent.session.seq - 1,
|
|
141
|
+
active: true,
|
|
142
|
+
running: agent.status === 'running',
|
|
143
|
+
queue: queueItems(agent),
|
|
144
|
+
pendingInput: this.pendingInput(agent.session.id),
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
const state = await this.historyController.usingObservation({ sessionId, projection: false }, signal, (observation) => {
|
|
148
|
+
// A live source means the Session attached during this read; report its live state
|
|
149
|
+
// rather than a live cursor paired with an inactive sample.
|
|
150
|
+
if (!retried && observation.source === 'live') return undefined
|
|
151
|
+
if (observation.header.cwd === undefined) rejectNotFound({ kind: 'session', sessionId })
|
|
152
|
+
return {
|
|
153
|
+
cursor: observation.cursor,
|
|
154
|
+
active: false,
|
|
155
|
+
running: false,
|
|
156
|
+
queue: null,
|
|
157
|
+
pendingInput: this.pendingInput(observation.header.id),
|
|
158
|
+
}
|
|
159
|
+
})
|
|
160
|
+
signal.throwIfAborted()
|
|
161
|
+
return state ?? this.readState(sessionId, signal, true)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
private pendingInput(sessionId: SessionId): readonly SessionPendingInput[] {
|
|
165
|
+
const kinds = new Set<SessionPendingInput>()
|
|
166
|
+
for (const { event, agentId } of this.ctx.typertGateway.getPendingRemoteEvents()) {
|
|
167
|
+
if (String(agentId) !== sessionId) continue
|
|
168
|
+
kinds.add(event === 'approval/request' ? 'approval' : event === 'user-questions/request' ? 'question' : 'other')
|
|
169
|
+
}
|
|
170
|
+
return [...kinds]
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* @param signal - wait deadline signal.
|
|
176
|
+
* @param error - failure raised by the in-flight read.
|
|
177
|
+
* @returns whether the deadline expired and cancelled that read.
|
|
178
|
+
*/
|
|
179
|
+
function expired(signal: AbortSignal, error: unknown): boolean {
|
|
180
|
+
const reason = timeoutOf(signal, 'session/wait-timeout')
|
|
181
|
+
if (reason === undefined) return false
|
|
182
|
+
// Cancellation carries the deadline reason along its cause chain; any other failure does not.
|
|
183
|
+
let current: unknown = error
|
|
184
|
+
for (let depth = 0; depth < 4 && current instanceof Error; depth++) {
|
|
185
|
+
if (current === reason || current.cause === reason) return true
|
|
186
|
+
current = current.cause
|
|
187
|
+
}
|
|
188
|
+
return error === reason
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Choose the next wait action; check-idle requires the caller's whenIdle and identity checks. */
|
|
192
|
+
function computeWaitAction(state: SessionState): 'input-required' | 'continue' | 'idle' | 'check-idle' {
|
|
193
|
+
if (state.pendingInput.length > 0) return 'input-required'
|
|
194
|
+
if (state.running) return 'continue'
|
|
195
|
+
if (!state.active) return 'idle'
|
|
196
|
+
return 'check-idle'
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Wait for either driver quiescence or the already-armed next state; preserve rejections from both. */
|
|
200
|
+
function waitForIdleOrStateChange(
|
|
201
|
+
agent: Agent,
|
|
202
|
+
nextStatePromise: Promise<IteratorResult<VersionedSessionState>>,
|
|
203
|
+
): Promise<'idle' | 'state-changed'> {
|
|
204
|
+
return Promise.race([
|
|
205
|
+
agent.whenIdle().then(() => 'idle' as const),
|
|
206
|
+
nextStatePromise.then(() => 'state-changed' as const),
|
|
207
|
+
])
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function queueItems(agent: Agent): SessionQueuedItem[] {
|
|
211
|
+
const item = (message: UserMessage, placement: SessionQueuedItem['placement']): SessionQueuedItem => ({
|
|
212
|
+
id: message.id,
|
|
213
|
+
placement,
|
|
214
|
+
...message.source.kind === 'user' && 'rpcId' in message.source ? { rpcId: message.source.rpcId } : {},
|
|
215
|
+
content: message.content as typeof message.content & readonly JsonValue[],
|
|
216
|
+
})
|
|
217
|
+
return [
|
|
218
|
+
...agent.inbox.nextTurn.map(message => item(message, 'queued')),
|
|
219
|
+
...agent.inbox.nextStep.map(message => item(message, message.source.kind === 'user' ? 'steering' : 'context')),
|
|
220
|
+
]
|
|
221
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/** Coalesced Session state observations with Host-local revisions. */
|
|
2
|
+
|
|
3
|
+
import type { Context } from '@unieai/cordis'
|
|
4
|
+
import type { SessionId } from '@unieai/rabi-session'
|
|
5
|
+
import type { SessionState } from '../types.ts'
|
|
6
|
+
|
|
7
|
+
/** One complete state with its listener-local revision. */
|
|
8
|
+
export interface VersionedSessionState { state: SessionState; revision: number }
|
|
9
|
+
|
|
10
|
+
/** Coalesces Session/Agent invalidations with local revisions; pending events are sampled on reads. */
|
|
11
|
+
export class StateListener implements Disposable {
|
|
12
|
+
private readonly disposes: (() => void)[] = []
|
|
13
|
+
private readonly cancellation = new AbortController()
|
|
14
|
+
private readonly signal: AbortSignal
|
|
15
|
+
private revision = 0
|
|
16
|
+
private resolver = createDeferredSignal()
|
|
17
|
+
private closed = false
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param ctx - lifecycle notification owner.
|
|
21
|
+
* @param target - Session to observe.
|
|
22
|
+
* @param signal - caller cancellation.
|
|
23
|
+
* @param readState - passive complete-state reader.
|
|
24
|
+
*/
|
|
25
|
+
constructor(
|
|
26
|
+
ctx: Context, target: SessionId, signal: AbortSignal,
|
|
27
|
+
private readonly readState: (signal: AbortSignal) => Promise<SessionState>,
|
|
28
|
+
) {
|
|
29
|
+
signal.throwIfAborted()
|
|
30
|
+
this.signal = AbortSignal.any([signal, this.cancellation.signal])
|
|
31
|
+
const notify = (id: string | undefined): void => {
|
|
32
|
+
if (id !== target || this.closed) return
|
|
33
|
+
this.revision++
|
|
34
|
+
const resolver = this.resolver
|
|
35
|
+
this.resolver = createDeferredSignal()
|
|
36
|
+
resolver.resolve()
|
|
37
|
+
}
|
|
38
|
+
const close = (): void => { this[Symbol.dispose]() }
|
|
39
|
+
signal.addEventListener('abort', close, { once: true })
|
|
40
|
+
this.disposes.push(() => { signal.removeEventListener('abort', close) })
|
|
41
|
+
try {
|
|
42
|
+
this.disposes.push(ctx.on('session/event', (session) => { notify(session.id) }, { global: true }))
|
|
43
|
+
this.disposes.push(ctx.on('session/created', (session) => { notify(session.id) }, { global: true }))
|
|
44
|
+
this.disposes.push(ctx.on('session/disposed', (session) => { notify(session.id) }, { global: true }))
|
|
45
|
+
this.disposes.push(ctx.on('agent/status', ({ agent }) => { notify(agent.id) }, { global: true }))
|
|
46
|
+
this.disposes.push(ctx.on('agent/created', ({ agent }) => { notify(agent.id) }, { global: true }))
|
|
47
|
+
this.disposes.push(ctx.on('agent/disposed', ({ agent }) => { notify(agent.id) }, { global: true }))
|
|
48
|
+
const dispose = ctx.effect(() => close, 'session-controller.state-listener')
|
|
49
|
+
this.disposes.push(() => { void dispose() })
|
|
50
|
+
} catch (error: unknown) {
|
|
51
|
+
this[Symbol.dispose]()
|
|
52
|
+
throw error
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Check whether a completed read still represents the latest invalidation.
|
|
58
|
+
* @param revision - revision captured with a completed read.
|
|
59
|
+
* @returns whether no intervening invalidation occurred.
|
|
60
|
+
*/
|
|
61
|
+
isCurrent(revision: number): boolean { return !this.closed && revision === this.revision }
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Read coalesced state replacements with optional periodic refresh.
|
|
65
|
+
* @param refreshMs - optional idle recheck interval; omitted for event-only observation.
|
|
66
|
+
* @returns complete state replacements with internal consistency revisions.
|
|
67
|
+
*/
|
|
68
|
+
async *observeStates(refreshMs?: number): AsyncGenerator<VersionedSessionState> {
|
|
69
|
+
let lastRevision = -1
|
|
70
|
+
try {
|
|
71
|
+
while (!this.closed) {
|
|
72
|
+
if (lastRevision === this.revision) {
|
|
73
|
+
if (refreshMs === undefined) {
|
|
74
|
+
await this.resolver.promise
|
|
75
|
+
} else {
|
|
76
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
77
|
+
try {
|
|
78
|
+
await Promise.race([
|
|
79
|
+
this.resolver.promise,
|
|
80
|
+
new Promise<void>((resolve) => { timer = setTimeout(resolve, refreshMs) }),
|
|
81
|
+
])
|
|
82
|
+
} finally {
|
|
83
|
+
clearTimeout(timer)
|
|
84
|
+
}
|
|
85
|
+
if (this.isCurrent(lastRevision)) {
|
|
86
|
+
this.revision++
|
|
87
|
+
const resolver = this.resolver
|
|
88
|
+
this.resolver = createDeferredSignal()
|
|
89
|
+
resolver.resolve()
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (!this.isCurrent(this.revision)) return
|
|
94
|
+
lastRevision = this.revision
|
|
95
|
+
const state = await this.readState(this.signal)
|
|
96
|
+
if (this.isCurrent(lastRevision)) yield { state, revision: lastRevision }
|
|
97
|
+
}
|
|
98
|
+
} finally {
|
|
99
|
+
this[Symbol.dispose]()
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
[Symbol.dispose](): void {
|
|
104
|
+
if (this.closed) return
|
|
105
|
+
this.closed = true
|
|
106
|
+
this.cancellation.abort()
|
|
107
|
+
this.resolver.resolve()
|
|
108
|
+
for (const dispose of this.disposes.splice(0).reverse()) dispose()
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function createDeferredSignal(): { promise: Promise<void>; resolve: () => void } {
|
|
113
|
+
let resolve!: () => void
|
|
114
|
+
const promise = new Promise<void>((settle) => { resolve = settle })
|
|
115
|
+
return { promise, resolve }
|
|
116
|
+
}
|