@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
package/src/control.ts
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/** Live Session projection state with reconnect baselines. */
|
|
2
|
+
|
|
3
|
+
import type { Context } from '@unieai/cordis'
|
|
4
|
+
import { Deque } from '@unieai/rabi-deque'
|
|
5
|
+
import type {
|
|
6
|
+
Session, SessionId,
|
|
7
|
+
} from '@unieai/rabi-session'
|
|
8
|
+
import type {
|
|
9
|
+
SessionControlBaseline,
|
|
10
|
+
SessionControlFrame,
|
|
11
|
+
SessionProjectionBaseline,
|
|
12
|
+
SessionProjectionUpdate,
|
|
13
|
+
SessionProjectionValues,
|
|
14
|
+
} from './types.ts'
|
|
15
|
+
|
|
16
|
+
/** Owns the Host-wide Session control stream. */
|
|
17
|
+
export class SessionControlController {
|
|
18
|
+
private readonly streams = new Set<ControlQueue>()
|
|
19
|
+
|
|
20
|
+
/** @param ctx - Host context carrying live Agent and projection services. */
|
|
21
|
+
constructor(private readonly ctx: Context) {
|
|
22
|
+
ctx.sessionProjections.onEventChanged((session, changes, seq) => {
|
|
23
|
+
this.broadcast({
|
|
24
|
+
type: 'projection',
|
|
25
|
+
sessionId: session.id,
|
|
26
|
+
seq,
|
|
27
|
+
// Every projection definition validates its value before change publication.
|
|
28
|
+
changes: changes as SessionProjectionUpdate['changes'],
|
|
29
|
+
})
|
|
30
|
+
})
|
|
31
|
+
ctx.effect(() => () => {
|
|
32
|
+
for (const stream of this.streams) stream.end()
|
|
33
|
+
this.streams.clear()
|
|
34
|
+
}, 'session-controller.control')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Open one generation of Host-wide live control state.
|
|
39
|
+
* @param signal - Remote stream cancellation.
|
|
40
|
+
* @returns one complete baseline followed by live replacement frames.
|
|
41
|
+
*/
|
|
42
|
+
async *control(signal: AbortSignal): AsyncIterable<SessionControlFrame> {
|
|
43
|
+
signal.throwIfAborted()
|
|
44
|
+
const queue = new ControlQueue()
|
|
45
|
+
this.streams.add(queue)
|
|
46
|
+
try {
|
|
47
|
+
yield { type: 'baseline', value: this.baseline() }
|
|
48
|
+
yield* queue.iterate(signal)
|
|
49
|
+
} finally {
|
|
50
|
+
this.streams.delete(queue)
|
|
51
|
+
queue.end()
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
private baseline(): SessionControlBaseline {
|
|
56
|
+
const sessions = this.ctx.sessions.list()
|
|
57
|
+
return {
|
|
58
|
+
projections: this.projectionBaseline(sessions),
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private projectionBaseline(
|
|
63
|
+
sessions: readonly Session[],
|
|
64
|
+
): Readonly<Record<SessionId, SessionProjectionBaseline>> {
|
|
65
|
+
const blocks = Object.create(null) as Record<SessionId, SessionProjectionBaseline>
|
|
66
|
+
for (const session of sessions) {
|
|
67
|
+
const snapshot = this.ctx.sessionProjections.snapshot(session)
|
|
68
|
+
blocks[session.id] = {
|
|
69
|
+
asOfSeq: snapshot.asOfSeq,
|
|
70
|
+
// Every projection definition validates its value before snapshot publication.
|
|
71
|
+
values: snapshot.values as SessionProjectionValues,
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return blocks
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
private broadcast(frame: SessionControlFrame): void {
|
|
78
|
+
for (const stream of this.streams) stream.push(frame)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
class ControlQueue {
|
|
83
|
+
private readonly buffer = new Deque<SessionControlFrame>()
|
|
84
|
+
private wake: (() => void) | undefined
|
|
85
|
+
private done = false
|
|
86
|
+
|
|
87
|
+
push(frame: SessionControlFrame): void {
|
|
88
|
+
if (this.done) return
|
|
89
|
+
this.buffer.pushBack(frame)
|
|
90
|
+
const wake = this.wake
|
|
91
|
+
this.wake = undefined
|
|
92
|
+
wake?.()
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
end(): void {
|
|
96
|
+
if (this.done) return
|
|
97
|
+
this.done = true
|
|
98
|
+
const wake = this.wake
|
|
99
|
+
this.wake = undefined
|
|
100
|
+
wake?.()
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async *iterate(signal: AbortSignal): AsyncIterable<SessionControlFrame> {
|
|
104
|
+
const onAbort = (): void => { this.end() }
|
|
105
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
106
|
+
try {
|
|
107
|
+
while (!this.done && !signal.aborted) {
|
|
108
|
+
const frame = this.buffer.popFront()
|
|
109
|
+
if (frame !== undefined) {
|
|
110
|
+
yield frame
|
|
111
|
+
continue
|
|
112
|
+
}
|
|
113
|
+
await new Promise<void>((resolve) => { this.wake = resolve })
|
|
114
|
+
}
|
|
115
|
+
while (this.buffer.size > 0 && !signal.aborted) yield this.buffer.popFront() as SessionControlFrame
|
|
116
|
+
} finally {
|
|
117
|
+
signal.removeEventListener('abort', onAbort)
|
|
118
|
+
this.end()
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Session Controller adapter for Agent-scoped file-reference discovery. */
|
|
2
|
+
|
|
3
|
+
import type { Context } from '@unieai/cordis'
|
|
4
|
+
import type { Agent } from '@unieai/rabi-agent'
|
|
5
|
+
import type {} from '@unieai/rabi-file-reference'
|
|
6
|
+
import type { FileReferenceCandidate } from '@unieai/rabi-file-reference/types'
|
|
7
|
+
import { Remote, TypertRemoteService } from '@unieai/rabi-typert-protocol'
|
|
8
|
+
|
|
9
|
+
declare module '@unieai/cordis' {
|
|
10
|
+
interface Context {
|
|
11
|
+
/** Host owner of the `fileReferences` Remote namespace. */
|
|
12
|
+
sessionFileReferences: SessionFileReferences
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Host Remote adapter over the composed file-reference provider. */
|
|
17
|
+
export class SessionFileReferences extends TypertRemoteService {
|
|
18
|
+
static inject = ['fileReferences', 'typert']
|
|
19
|
+
|
|
20
|
+
/** @param ctx - Host context carrying the selected file-reference provider. */
|
|
21
|
+
constructor(ctx: Context) {
|
|
22
|
+
super(ctx, 'sessionFileReferences', { namespace: 'fileReferences' })
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* List file and directory candidates for one Agent's working directory.
|
|
27
|
+
* @param agent - target Agent resolved from the Session identity on the wire.
|
|
28
|
+
* @param query - path text following `@` or `@"`.
|
|
29
|
+
* @param signal - caller cancellation.
|
|
30
|
+
* @returns deterministic path-only candidates from the composed provider.
|
|
31
|
+
*/
|
|
32
|
+
@Remote
|
|
33
|
+
list(
|
|
34
|
+
agent: Agent,
|
|
35
|
+
query: string,
|
|
36
|
+
signal: AbortSignal,
|
|
37
|
+
): Promise<FileReferenceCandidate[]> {
|
|
38
|
+
return this.ctx.fileReferences.list(agent, query, signal)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export default SessionFileReferences
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/** Assistant stream baselines and per-connection subscriptions. */
|
|
2
|
+
|
|
3
|
+
import type { Context } from '@unieai/cordis'
|
|
4
|
+
import { SessionSeq } from '@unieai/rabi-session'
|
|
5
|
+
import type { Session, SessionId } from '@unieai/rabi-session'
|
|
6
|
+
import type { JsonValue } from '@unieai/rabi-util-values'
|
|
7
|
+
import { SessionAssistantStreamAccumulator } from '../assistant-stream.ts'
|
|
8
|
+
import type { SessionAssistantStreamBaseline, SessionAssistantStreamFrame } from '../types.ts'
|
|
9
|
+
import { ListenerBuffer } from './listener.ts'
|
|
10
|
+
|
|
11
|
+
/** One accumulator per live Session, shared by every subscription bound to it. */
|
|
12
|
+
export class SessionAssistantStreamsListener {
|
|
13
|
+
private readonly streams = new Map<SessionId, SessionAssistantStreamAccumulator>()
|
|
14
|
+
|
|
15
|
+
/** @param ctx - service context owning the accumulator listeners. */
|
|
16
|
+
constructor(private readonly ctx: Context) {
|
|
17
|
+
ctx.on('agent/assistant-stream', ({ agent, frame }) => {
|
|
18
|
+
let stream = this.streams.get(agent.session.id)
|
|
19
|
+
if (stream === undefined) {
|
|
20
|
+
stream = new SessionAssistantStreamAccumulator()
|
|
21
|
+
this.streams.set(agent.session.id, stream)
|
|
22
|
+
}
|
|
23
|
+
stream.accept(frame, agent.session.seq === 0 ? -1 : SessionSeq(agent.session.seq - 1))
|
|
24
|
+
}, { global: true })
|
|
25
|
+
ctx.on('agent/disposed', ({ agent }) => { this.streams.delete(agent.session.id) }, { global: true })
|
|
26
|
+
ctx.effect(() => () => { this.streams.clear() }, 'session-controller.assistant-streams')
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Bind one connection to a Session assistant stream.
|
|
31
|
+
* @param sessionId - Session to subscribe.
|
|
32
|
+
* @param signal - cancellation owned by the caller.
|
|
33
|
+
* @param queue - caller-owned raw notification buffer.
|
|
34
|
+
* @returns a listener the caller disposes.
|
|
35
|
+
*/
|
|
36
|
+
bind(sessionId: SessionId, signal: AbortSignal,
|
|
37
|
+
queue: Pick<ListenerBuffer<AssistantEntry>, 'createInput' | 'capture'>): AssistantStreamListener {
|
|
38
|
+
return new AssistantStreamListener(this.ctx, sessionId, signal, () => {
|
|
39
|
+
return this.streams.get(sessionId)?.snapshot() ?? { revision: 0 }
|
|
40
|
+
}, queue)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
type AssistantEntry = { type: 'assistant-stream'; frame: SessionAssistantStreamFrame }
|
|
45
|
+
|
|
46
|
+
/** An assistant notification and its connection-local arrival position. */
|
|
47
|
+
interface AssistantItem {
|
|
48
|
+
readonly type: 'assistant-stream'
|
|
49
|
+
readonly session: Session
|
|
50
|
+
readonly frame: SessionAssistantStreamFrame
|
|
51
|
+
readonly ordinal: number
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Writes assistant notifications into the connection's shared queue. */
|
|
55
|
+
class AssistantStreamListener implements Disposable {
|
|
56
|
+
private readonly disposes: (() => void)[] = []
|
|
57
|
+
private ordinal = 0
|
|
58
|
+
private cut = 0
|
|
59
|
+
|
|
60
|
+
constructor(
|
|
61
|
+
ctx: Context,
|
|
62
|
+
sessionId: SessionId,
|
|
63
|
+
signal: AbortSignal,
|
|
64
|
+
private _snapshot: () => SessionAssistantStreamBaseline,
|
|
65
|
+
output: Pick<ListenerBuffer<AssistantEntry>, 'createInput' | 'capture'>) {
|
|
66
|
+
signal.throwIfAborted()
|
|
67
|
+
const input = output.createInput<AssistantItem>(item => this.transform(item))
|
|
68
|
+
try {
|
|
69
|
+
this.disposes.push(ctx.on('agent/assistant-stream', ({ agent, frame }) => {
|
|
70
|
+
if (agent.session.id !== sessionId) return
|
|
71
|
+
output.capture(() => {
|
|
72
|
+
const wire: SessionAssistantStreamFrame = frame.type === 'start'
|
|
73
|
+
? { ...frame, startedAfterSeq: agent.session.seq === 0 ? -1 : SessionSeq(agent.session.seq - 1) }
|
|
74
|
+
: frame.type === 'chunk' ? { ...frame, chunk: frame.chunk as JsonValue } : frame
|
|
75
|
+
input.append({ type: 'assistant-stream', session: agent.session, frame: wire, ordinal: ++this.ordinal })
|
|
76
|
+
})
|
|
77
|
+
}, { global: true }))
|
|
78
|
+
} catch (error: unknown) {
|
|
79
|
+
this[Symbol.dispose]()
|
|
80
|
+
throw error
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** @returns the baseline and local arrival cut captured synchronously together. */
|
|
85
|
+
snapshot(): { baseline: SessionAssistantStreamBaseline; ordinal: number } {
|
|
86
|
+
return { baseline: this._snapshot(), ordinal: this.ordinal }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** @param ordinal - local snapshot cut set before queue consumption. */
|
|
90
|
+
setOrdinalCut(ordinal: number): void {
|
|
91
|
+
this.cut = ordinal
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
private *transform(item: AssistantItem): Iterable<AssistantEntry> {
|
|
95
|
+
if (this.disposes.length === 0 || item.ordinal <= this.cut) return
|
|
96
|
+
yield { type: 'assistant-stream', frame: item.frame }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
[Symbol.dispose](): void {
|
|
100
|
+
for (const dispose of this.disposes.splice(0).reverse()) dispose()
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/** Independent Session snapshots and passive event subscriptions. */
|
|
2
|
+
|
|
3
|
+
import type { Context } from '@unieai/cordis'
|
|
4
|
+
import { SessionLogOffset, SessionSeq, isAppendSurfaceEvent } from '@unieai/rabi-session'
|
|
5
|
+
import type { SessionId, SessionEvent } from '@unieai/rabi-session'
|
|
6
|
+
import type { SessionObservation } from '@unieai/rabi-session-query'
|
|
7
|
+
import { RemoteError, remoteErrorOf } from '@unieai/rabi-typert-protocol'
|
|
8
|
+
import {
|
|
9
|
+
DEFAULT_MAX_MESSAGES, paginate, pageRecords, entryFor, addressId,
|
|
10
|
+
validateHistoryWindow, validateAddress, rejectNotFound,
|
|
11
|
+
} from '../history.ts'
|
|
12
|
+
import { EventListener, ProjectionListener } from './listener.ts'
|
|
13
|
+
import { SessionAssistantStreamsListener } from './assistant-stream.ts'
|
|
14
|
+
import type {
|
|
15
|
+
SessionEventFrame, SessionEventsPage, SessionPageRequest,
|
|
16
|
+
SessionObserveEventRequest, SessionProjectionsRequest, SessionProjectionFrame,
|
|
17
|
+
SessionAddress, SessionProjectionBaseline, SessionProjectionValues, SessionProjectionsValue, SessionWaitOutput, SessionHistoryRecord,
|
|
18
|
+
} from '../types.ts'
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
/** Session snapshots do not share lifetime with passive subscriptions. */
|
|
22
|
+
export class HistoryController {
|
|
23
|
+
|
|
24
|
+
/** Reconnect state for this controller's assistant subscriptions. */
|
|
25
|
+
readonly streamsListener: SessionAssistantStreamsListener
|
|
26
|
+
|
|
27
|
+
/** @param ctx - Host context carrying Session reads and projections. */
|
|
28
|
+
constructor(private readonly ctx: Context) {
|
|
29
|
+
this.streamsListener = new SessionAssistantStreamsListener(this.ctx)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Read a passive page of Session events at an exact cut.
|
|
34
|
+
* @param request - Session identity and optional cut and page window.
|
|
35
|
+
* @param signal - read cancellation.
|
|
36
|
+
* @returns a page at the supplied cut, or the observed log end when omitted.
|
|
37
|
+
*/
|
|
38
|
+
async events(request: SessionPageRequest, signal: AbortSignal): Promise<SessionEventsPage> {
|
|
39
|
+
const spec = resolveHistoryRequest(request)
|
|
40
|
+
try {
|
|
41
|
+
return await this.usingObservation({ sessionId: addressId(request.address), projection: request.address.kind === 'subagent' }, signal, (observation) => {
|
|
42
|
+
validateObservationAddress(request.address, observation)
|
|
43
|
+
return history(observation, spec)
|
|
44
|
+
})
|
|
45
|
+
} catch (error: unknown) {
|
|
46
|
+
if (remoteErrorOf(error)?.code === 'session/not-found') rejectNotFound(request.address)
|
|
47
|
+
throw error
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Subscribe to Session events without reading or activating the Session.
|
|
53
|
+
* @param request - Session address to subscribe.
|
|
54
|
+
* @param signal - stream cancellation.
|
|
55
|
+
* @returns subscription readiness followed by event frames; readiness does not establish existence.
|
|
56
|
+
*/
|
|
57
|
+
async *observeEvent(request: SessionObserveEventRequest, signal: AbortSignal): AsyncIterable<SessionEventFrame> {
|
|
58
|
+
using listener = new EventListener(this.ctx, addressId(request.address), signal)
|
|
59
|
+
yield { type: 'ready' }
|
|
60
|
+
yield* listener.events()
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Read exact projections or migration cache hints without activating the Session.
|
|
65
|
+
* @param request - Session identity whose exact projection baseline is required.
|
|
66
|
+
* @param signal - read cancellation.
|
|
67
|
+
* @returns exact sequenced values, migration cache hints, or null when absent.
|
|
68
|
+
*/
|
|
69
|
+
async projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise<SessionProjectionsValue> {
|
|
70
|
+
const { sessionId } = request
|
|
71
|
+
if (sessionId.length === 0) {
|
|
72
|
+
throw new RemoteError('gateway/bad-request', 'sessionId must not be empty', {})
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
signal.throwIfAborted()
|
|
76
|
+
const live = this.ctx.sessions.get(sessionId)
|
|
77
|
+
if (live !== undefined) {
|
|
78
|
+
const snapshot = this.ctx.sessionProjections.snapshot(live)
|
|
79
|
+
return { kind: 'sequenced', asOfSeq: snapshot.asOfSeq, values: snapshot.values as SessionProjectionValues }
|
|
80
|
+
} else {
|
|
81
|
+
const stored = await this.ctx.get('sessionPersistence')?.stat(sessionId, { signal })
|
|
82
|
+
signal.throwIfAborted()
|
|
83
|
+
if (stored?.formatStatus === 'migration-required') {
|
|
84
|
+
const cached = this.ctx.get('sessionProjectionCache')?.cachedSnapshot(stored.header)
|
|
85
|
+
return { kind: 'migration-required', values: { ...cached?.values } as SessionProjectionValues }
|
|
86
|
+
}
|
|
87
|
+
return await this.usingObservation({ sessionId: request.sessionId, projection: true }, signal, observation => ({
|
|
88
|
+
kind: 'sequenced' as const,
|
|
89
|
+
...projections(observation),
|
|
90
|
+
}))
|
|
91
|
+
}
|
|
92
|
+
} catch (error: unknown) {
|
|
93
|
+
const code = typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined
|
|
94
|
+
if (code === 'SESSION_QUERY_SESSION_NOT_FOUND' || code === 'session/not-found') {
|
|
95
|
+
return null
|
|
96
|
+
}
|
|
97
|
+
if (signal.aborted || code === 'SESSION_QUERY_ABORTED') {
|
|
98
|
+
throw new RemoteError('gateway/cancelled', 'Session projection read was cancelled', {}, { cause: error })
|
|
99
|
+
}
|
|
100
|
+
if (remoteErrorOf(error) !== undefined) throw error
|
|
101
|
+
throw new RemoteError('gateway/internal', 'Session projection read failed', {}, { cause: error })
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Subscribe to projection changes without reading a baseline.
|
|
107
|
+
* @param request - Session identity to subscribe without reading a baseline.
|
|
108
|
+
* @param signal - stream cancellation.
|
|
109
|
+
* @returns readiness followed by one change frame per committed event, listing every key it changed.
|
|
110
|
+
*/
|
|
111
|
+
async *observeProjections(request: SessionProjectionsRequest, signal: AbortSignal): AsyncIterable<SessionProjectionFrame> {
|
|
112
|
+
using listener = new ProjectionListener(this.ctx, request.sessionId, signal)
|
|
113
|
+
yield { type: 'ready' }
|
|
114
|
+
yield* listener.changes()
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Read bounded committed assistant messages through a stopping cursor.
|
|
119
|
+
* @param sessionId - Session whose committed assistant messages are requested.
|
|
120
|
+
* @param afterSeq - exclusive lower bound.
|
|
121
|
+
* @param throughSeq - inclusive stopping-state cursor.
|
|
122
|
+
* @param maxMessages - positive assistant record limit.
|
|
123
|
+
* @param signal - caller cancellation, independent of a completed wait deadline.
|
|
124
|
+
* @returns newest-first assistant messages and whether further matching records were omitted.
|
|
125
|
+
*/
|
|
126
|
+
async assistantOutput(
|
|
127
|
+
sessionId: SessionId, afterSeq: number, throughSeq: number, maxMessages: number, signal: AbortSignal,
|
|
128
|
+
): Promise<SessionWaitOutput> {
|
|
129
|
+
return this.usingObservation({ sessionId, projection: false }, signal, (observation) => {
|
|
130
|
+
if (throughSeq > observation.cursor) {
|
|
131
|
+
throw new RemoteError('gateway/internal', 'Session history no longer covers the wait cursor', {})
|
|
132
|
+
}
|
|
133
|
+
const records: SessionHistoryRecord[] = []
|
|
134
|
+
const events = observation.events
|
|
135
|
+
for (let index = throughSeq; index > afterSeq; index--) {
|
|
136
|
+
const event = events[index] as SessionEvent
|
|
137
|
+
if (event.type !== 'assistant/message' || !isAppendSurfaceEvent(event)) continue
|
|
138
|
+
if (records.length === maxMessages) return { records, truncated: true }
|
|
139
|
+
records.push(entryFor(event))
|
|
140
|
+
}
|
|
141
|
+
return { records, truncated: false }
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Acquire a read without activating a Session; projections are opt-in.
|
|
147
|
+
* @param request - Session identity and whether to compute projections.
|
|
148
|
+
* @param signal - read cancellation.
|
|
149
|
+
* @param callback - omitted to transfer lease ownership to the caller.
|
|
150
|
+
* @returns a lease the caller must dispose.
|
|
151
|
+
*/
|
|
152
|
+
usingObservation(
|
|
153
|
+
request: { readonly sessionId: SessionId; readonly projection: boolean }, signal: AbortSignal, callback?: undefined,
|
|
154
|
+
): Promise<SessionObservation>
|
|
155
|
+
/**
|
|
156
|
+
* Keep the borrowed lease alive until the callback settles, then dispose it.
|
|
157
|
+
* @param request - Session identity and whether to compute projections.
|
|
158
|
+
* @param signal - read cancellation.
|
|
159
|
+
* @param callback - synchronous or asynchronous computation; retain a separate lease if it must escape.
|
|
160
|
+
* @returns the callback result; read and callback failures propagate.
|
|
161
|
+
*/
|
|
162
|
+
usingObservation<T>(
|
|
163
|
+
request: { readonly sessionId: SessionId; readonly projection: boolean }, signal: AbortSignal,
|
|
164
|
+
callback: (observation: SessionObservation) => T,
|
|
165
|
+
): Promise<Awaited<T>>
|
|
166
|
+
async usingObservation<T>(
|
|
167
|
+
{ sessionId, projection }: { readonly sessionId: SessionId; readonly projection: boolean }, signal: AbortSignal,
|
|
168
|
+
callback?: (observation: SessionObservation) => T,
|
|
169
|
+
): Promise<SessionObservation | Awaited<T>> {
|
|
170
|
+
let observation: SessionObservation
|
|
171
|
+
try {
|
|
172
|
+
observation = await this.ctx.sessionQuery.observeSession(sessionId, { signal, projectionMode: projection ? 'all' : 'none' })
|
|
173
|
+
} catch (error: unknown) {
|
|
174
|
+
const code = (error as { readonly code?: unknown } | null | undefined)?.code
|
|
175
|
+
if (code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
|
|
176
|
+
throw new RemoteError('session/not-found', `session "${sessionId}" not found`, { sessionId })
|
|
177
|
+
}
|
|
178
|
+
if (code === 'SESSION_QUERY_ABORTED') {
|
|
179
|
+
// Keep the query's own message: cancellation detail was visible before this mapping.
|
|
180
|
+
throw new RemoteError('gateway/cancelled',
|
|
181
|
+
error instanceof Error ? error.message : 'Session read was cancelled', {}, { cause: error })
|
|
182
|
+
}
|
|
183
|
+
throw error
|
|
184
|
+
}
|
|
185
|
+
try {
|
|
186
|
+
signal.throwIfAborted()
|
|
187
|
+
} catch (error: unknown) {
|
|
188
|
+
observation[Symbol.dispose]()
|
|
189
|
+
throw error
|
|
190
|
+
}
|
|
191
|
+
if (callback === undefined) return observation
|
|
192
|
+
using ownedObservation = observation
|
|
193
|
+
return await callback(ownedObservation)
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Validate an Address against the exact read used by a Controller.
|
|
199
|
+
* @param address - caller-supplied Session address.
|
|
200
|
+
* @param observation - borrowed read; subagent addresses require projections.
|
|
201
|
+
*/
|
|
202
|
+
export function validateObservationAddress(address: SessionAddress, observation: SessionObservation): void {
|
|
203
|
+
if (observation.header.cwd === undefined) rejectNotFound(address)
|
|
204
|
+
validateAddress(address, observation.header, observation.inheritedEventCount, observation.projections)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Convert a borrowed observation to one page without acquiring or retaining it.
|
|
209
|
+
* @param observation - exact read cut owned by the caller.
|
|
210
|
+
* @param request - validated page window and optional inclusive cut.
|
|
211
|
+
* @returns a chronological page at the requested cut.
|
|
212
|
+
*/
|
|
213
|
+
export function history(observation: SessionObservation, request: Omit<SessionPageRequest, 'address'> & { readonly maxMessages: number }): SessionEventsPage {
|
|
214
|
+
const cursor = request.throughSeq === undefined ? observation.cursor
|
|
215
|
+
: request.throughSeq === -1 ? -1 : SessionSeq(request.throughSeq)
|
|
216
|
+
if (cursor > observation.cursor) {
|
|
217
|
+
throw new RemoteError('gateway/bad-request', `session history cut ${String(cursor)} exceeds ${String(observation.cursor)}`, {})
|
|
218
|
+
}
|
|
219
|
+
const page = paginate(
|
|
220
|
+
observation.events,
|
|
221
|
+
request.beforeSeq === undefined ? undefined : SessionLogOffset(request.beforeSeq),
|
|
222
|
+
request.maxMessages,
|
|
223
|
+
cursor,
|
|
224
|
+
request.turnWindow,
|
|
225
|
+
)
|
|
226
|
+
return { cursor, records: pageRecords(page.events), hasMore: page.hasMore }
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Convert the projection baseline without acquiring or retaining its observation.
|
|
231
|
+
* @param observation - projected read cut owned by the caller.
|
|
232
|
+
* @returns the exact baseline; missing projection support fails explicitly.
|
|
233
|
+
*/
|
|
234
|
+
export function projections(observation: SessionObservation): SessionProjectionBaseline {
|
|
235
|
+
const snapshot = observation.projections
|
|
236
|
+
if (snapshot === undefined) throw new RemoteError('session/projections-unavailable', 'Session projections are unavailable', {})
|
|
237
|
+
return { asOfSeq: snapshot.asOfSeq, values: snapshot.values as SessionProjectionValues }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Validate and resolve the history page window.
|
|
242
|
+
* @param request - external history window.
|
|
243
|
+
* @returns the validated request with an explicit message budget.
|
|
244
|
+
*/
|
|
245
|
+
export function resolveHistoryRequest(request: SessionPageRequest): SessionPageRequest & { readonly maxMessages: number } {
|
|
246
|
+
if (request.throughSeq !== undefined
|
|
247
|
+
&& (!Number.isSafeInteger(request.throughSeq) || request.throughSeq < -1 || Object.is(request.throughSeq, -0))) {
|
|
248
|
+
throw new RemoteError('gateway/bad-request', 'throughSeq must be an integer greater than or equal to -1', {})
|
|
249
|
+
}
|
|
250
|
+
if (request.beforeSeq !== undefined
|
|
251
|
+
&& (!Number.isSafeInteger(request.beforeSeq) || request.beforeSeq < 0 || Object.is(request.beforeSeq, -0))) {
|
|
252
|
+
throw new RemoteError('gateway/bad-request', 'beforeSeq must be a non-negative safe integer', {})
|
|
253
|
+
}
|
|
254
|
+
validateHistoryWindow(request)
|
|
255
|
+
return { ...request, maxMessages: request.maxMessages ?? DEFAULT_MAX_MESSAGES }
|
|
256
|
+
}
|