@unieai/rabi-api-session-controller 0.0.0-stage → 0.2.1-rc.3
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 +4325 -0
- package/lib/index.js +3367 -0
- package/lib/typert.host.d.ts +3 -0
- package/lib/typert.host.js +4053 -0
- package/lib/typert.remote-client.d.ts +97 -0
- package/lib/typert.remote-client.js +2013 -0
- package/lib/types/agent.d.ts +198 -0
- package/lib/types/agent.js +609 -0
- package/lib/types/archived-session-gate.d.ts +30 -0
- package/lib/types/archived-session-gate.js +51 -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 +106 -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 +157 -0
- package/lib/types/client/contract/session.js +1 -0
- package/lib/types/client/contract/sessions.d.ts +161 -0
- package/lib/types/client/contract/sessions.js +1 -0
- package/lib/types/client/contract/snapshot.d.ts +81 -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 +40 -0
- package/lib/types/client/sessions/lineage.js +54 -0
- package/lib/types/client/sessions/manager.d.ts +269 -0
- package/lib/types/client/sessions/manager.js +799 -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 +258 -0
- package/lib/types/client/sessions/service.js +582 -0
- package/lib/types/client/sessions/session.d.ts +287 -0
- package/lib/types/client/sessions/session.js +866 -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 +129 -0
- package/lib/types/commands.d.ts +86 -0
- package/lib/types/commands.js +624 -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.d.ts +32 -0
- package/lib/types/history.js +441 -0
- package/lib/types/index.d.ts +222 -0
- package/lib/types/index.js +658 -0
- package/lib/types/list.d.ts +50 -0
- package/lib/types/list.js +325 -0
- package/lib/types/media-references.d.ts +16 -0
- package/lib/types/media-references.js +76 -0
- package/lib/types/model-selection-projection.d.ts +8 -0
- package/lib/types/model-selection-projection.js +65 -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/types.d.ts +611 -0
- package/lib/types/types.js +4 -0
- package/locale/en.json +5 -0
- package/locale/zh.json +6 -0
- package/package.json +114 -4
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/** Live Session projection state with reconnect baselines. */
|
|
2
|
+
import { Deque } from '@unieai/rabi-deque';
|
|
3
|
+
/** Owns the Host-wide Session control stream. */
|
|
4
|
+
export class SessionControlController {
|
|
5
|
+
ctx;
|
|
6
|
+
streams = new Set();
|
|
7
|
+
/** @param ctx - Host context carrying live Agent and projection services. */
|
|
8
|
+
constructor(ctx) {
|
|
9
|
+
this.ctx = ctx;
|
|
10
|
+
ctx.sessionProjections.onChanged((session, key, value, seq) => {
|
|
11
|
+
this.broadcast({
|
|
12
|
+
type: 'projection',
|
|
13
|
+
sessionId: session.id,
|
|
14
|
+
key,
|
|
15
|
+
value: value,
|
|
16
|
+
seq,
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
ctx.effect(() => () => {
|
|
20
|
+
for (const stream of this.streams)
|
|
21
|
+
stream.end();
|
|
22
|
+
this.streams.clear();
|
|
23
|
+
}, 'session-controller.control');
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Open one generation of Host-wide live control state.
|
|
27
|
+
* @param signal - Remote stream cancellation.
|
|
28
|
+
* @returns one complete baseline followed by live replacement frames.
|
|
29
|
+
*/
|
|
30
|
+
async *control(signal) {
|
|
31
|
+
signal.throwIfAborted();
|
|
32
|
+
const queue = new ControlQueue();
|
|
33
|
+
this.streams.add(queue);
|
|
34
|
+
try {
|
|
35
|
+
yield { type: 'baseline', value: this.baseline() };
|
|
36
|
+
yield* queue.iterate(signal);
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
this.streams.delete(queue);
|
|
40
|
+
queue.end();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
baseline() {
|
|
44
|
+
const sessions = this.ctx.sessions.list();
|
|
45
|
+
return {
|
|
46
|
+
projections: this.projectionBaseline(sessions),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
projectionBaseline(sessions) {
|
|
50
|
+
const blocks = Object.create(null);
|
|
51
|
+
for (const session of sessions) {
|
|
52
|
+
const snapshot = this.ctx.sessionProjections.snapshot(session);
|
|
53
|
+
blocks[session.id] = {
|
|
54
|
+
asOfSeq: snapshot.asOfSeq,
|
|
55
|
+
// Every projection definition validates its value before snapshot publication.
|
|
56
|
+
values: snapshot.values,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
return blocks;
|
|
60
|
+
}
|
|
61
|
+
broadcast(frame) {
|
|
62
|
+
for (const stream of this.streams)
|
|
63
|
+
stream.push(frame);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
class ControlQueue {
|
|
67
|
+
buffer = new Deque();
|
|
68
|
+
wake;
|
|
69
|
+
done = false;
|
|
70
|
+
push(frame) {
|
|
71
|
+
if (this.done)
|
|
72
|
+
return;
|
|
73
|
+
this.buffer.pushBack(frame);
|
|
74
|
+
const wake = this.wake;
|
|
75
|
+
this.wake = undefined;
|
|
76
|
+
wake?.();
|
|
77
|
+
}
|
|
78
|
+
end() {
|
|
79
|
+
if (this.done)
|
|
80
|
+
return;
|
|
81
|
+
this.done = true;
|
|
82
|
+
const wake = this.wake;
|
|
83
|
+
this.wake = undefined;
|
|
84
|
+
wake?.();
|
|
85
|
+
}
|
|
86
|
+
async *iterate(signal) {
|
|
87
|
+
const onAbort = () => { this.end(); };
|
|
88
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
89
|
+
try {
|
|
90
|
+
while (!this.done && !signal.aborted) {
|
|
91
|
+
const frame = this.buffer.popFront();
|
|
92
|
+
if (frame !== undefined) {
|
|
93
|
+
yield frame;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
await new Promise((resolve) => { this.wake = resolve; });
|
|
97
|
+
}
|
|
98
|
+
while (this.buffer.size > 0 && !signal.aborted)
|
|
99
|
+
yield this.buffer.popFront();
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
signal.removeEventListener('abort', onAbort);
|
|
103
|
+
this.end();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Session Controller adapter for Agent-scoped file-reference discovery. */
|
|
2
|
+
import type { Context } from '@unieai/cordis';
|
|
3
|
+
import type { Agent } from '@unieai/rabi-agent';
|
|
4
|
+
import type { FileReferenceCandidate } from '@unieai/rabi-file-reference/types';
|
|
5
|
+
import { TypertRemoteService } from '@unieai/rabi-typert-protocol';
|
|
6
|
+
declare module '@unieai/cordis' {
|
|
7
|
+
interface Context {
|
|
8
|
+
/** Host owner of the `fileReferences` Remote namespace. */
|
|
9
|
+
sessionFileReferences: SessionFileReferences;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Host Remote adapter over the composed file-reference provider. */
|
|
13
|
+
export declare class SessionFileReferences extends TypertRemoteService {
|
|
14
|
+
static inject: string[];
|
|
15
|
+
/** @param ctx - Host context carrying the selected file-reference provider. */
|
|
16
|
+
constructor(ctx: Context);
|
|
17
|
+
/**
|
|
18
|
+
* List file and directory candidates for one Agent's working directory.
|
|
19
|
+
* @param agent - target Agent resolved from the Session identity on the wire.
|
|
20
|
+
* @param query - path text following `@` or `@"`.
|
|
21
|
+
* @param signal - caller cancellation.
|
|
22
|
+
* @returns deterministic path-only candidates from the composed provider.
|
|
23
|
+
*/
|
|
24
|
+
list(agent: Agent, query: string, signal: AbortSignal): Promise<FileReferenceCandidate[]>;
|
|
25
|
+
}
|
|
26
|
+
export default SessionFileReferences;
|
|
27
|
+
//# sourceMappingURL=file-references.d.ts.map
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/** Session Controller adapter for Agent-scoped file-reference discovery. */
|
|
2
|
+
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
|
|
3
|
+
var useValue = arguments.length > 2;
|
|
4
|
+
for (var i = 0; i < initializers.length; i++) {
|
|
5
|
+
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
|
|
6
|
+
}
|
|
7
|
+
return useValue ? value : void 0;
|
|
8
|
+
};
|
|
9
|
+
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
|
|
10
|
+
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
|
|
11
|
+
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
|
|
12
|
+
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
|
|
13
|
+
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
|
|
14
|
+
var _, done = false;
|
|
15
|
+
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
16
|
+
var context = {};
|
|
17
|
+
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
|
|
18
|
+
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
|
|
19
|
+
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
|
|
20
|
+
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
|
|
21
|
+
if (kind === "accessor") {
|
|
22
|
+
if (result === void 0) continue;
|
|
23
|
+
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
|
|
24
|
+
if (_ = accept(result.get)) descriptor.get = _;
|
|
25
|
+
if (_ = accept(result.set)) descriptor.set = _;
|
|
26
|
+
if (_ = accept(result.init)) initializers.unshift(_);
|
|
27
|
+
}
|
|
28
|
+
else if (_ = accept(result)) {
|
|
29
|
+
if (kind === "field") initializers.unshift(_);
|
|
30
|
+
else descriptor[key] = _;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (target) Object.defineProperty(target, contextIn.name, descriptor);
|
|
34
|
+
done = true;
|
|
35
|
+
};
|
|
36
|
+
import { Remote, TypertRemoteService } from '@unieai/rabi-typert-protocol';
|
|
37
|
+
/** Host Remote adapter over the composed file-reference provider. */
|
|
38
|
+
let SessionFileReferences = (() => {
|
|
39
|
+
let _classSuper = TypertRemoteService;
|
|
40
|
+
let _instanceExtraInitializers = [];
|
|
41
|
+
let _list_decorators;
|
|
42
|
+
return class SessionFileReferences extends _classSuper {
|
|
43
|
+
static {
|
|
44
|
+
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
|
|
45
|
+
_list_decorators = [Remote];
|
|
46
|
+
__esDecorate(this, null, _list_decorators, { kind: "method", name: "list", static: false, private: false, access: { has: obj => "list" in obj, get: obj => obj.list }, metadata: _metadata }, null, _instanceExtraInitializers);
|
|
47
|
+
if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
|
|
48
|
+
}
|
|
49
|
+
static inject = ['fileReferences', 'typert'];
|
|
50
|
+
/** @param ctx - Host context carrying the selected file-reference provider. */
|
|
51
|
+
constructor(ctx) {
|
|
52
|
+
super(ctx, 'sessionFileReferences', { namespace: 'fileReferences' });
|
|
53
|
+
__runInitializers(this, _instanceExtraInitializers);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* List file and directory candidates for one Agent's working directory.
|
|
57
|
+
* @param agent - target Agent resolved from the Session identity on the wire.
|
|
58
|
+
* @param query - path text following `@` or `@"`.
|
|
59
|
+
* @param signal - caller cancellation.
|
|
60
|
+
* @returns deterministic path-only candidates from the composed provider.
|
|
61
|
+
*/
|
|
62
|
+
list(agent, query, signal) {
|
|
63
|
+
return this.ctx.fileReferences.list(agent, query, signal);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
})();
|
|
67
|
+
export { SessionFileReferences };
|
|
68
|
+
export default SessionFileReferences;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Cold Session history pagination and live-event source. */
|
|
2
|
+
import type { Context } from '@unieai/cordis';
|
|
3
|
+
import { type SessionObservation } from '@unieai/rabi-session-query';
|
|
4
|
+
import type { SessionFollowRequest, SessionFollowFrame, SessionPage, SessionPageRequest } from './types.ts';
|
|
5
|
+
/** Implements cold-safe history operations delegated by the Session Controller. */
|
|
6
|
+
export declare class SessionHistoryController {
|
|
7
|
+
private readonly ctx;
|
|
8
|
+
private readonly promote;
|
|
9
|
+
private readonly closeFollowers;
|
|
10
|
+
private readonly assistantStreams;
|
|
11
|
+
/**
|
|
12
|
+
* @param ctx - Host context carrying Session query and projection services.
|
|
13
|
+
* @param promote - starts ordinary Session activation after snapshot delivery.
|
|
14
|
+
*/
|
|
15
|
+
constructor(ctx: Context, promote: (observation: SessionObservation) => void);
|
|
16
|
+
/**
|
|
17
|
+
* Read one message-aligned history page without activating an Agent.
|
|
18
|
+
* @param request - durable address and backwards-page cursor.
|
|
19
|
+
* @param signal - caller cancellation for persistence reads.
|
|
20
|
+
* @returns a contiguous event page.
|
|
21
|
+
*/
|
|
22
|
+
page(request: SessionPageRequest, signal: AbortSignal): Promise<SessionPage>;
|
|
23
|
+
/**
|
|
24
|
+
* Follow events appended after an initial cursor on one durable address.
|
|
25
|
+
* @param request - durable address and last committed sequence already held by the caller.
|
|
26
|
+
* @param signal - stream cancellation owned by the Remote carrier.
|
|
27
|
+
* @returns a complete opening snapshot followed by gap-free durable events and opted-in assistant frames.
|
|
28
|
+
*/
|
|
29
|
+
follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable<SessionFollowFrame>;
|
|
30
|
+
private sourceFor;
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=history.d.ts.map
|
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
/** Cold Session history pagination and live-event source. */
|
|
2
|
+
var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
|
|
3
|
+
if (value !== null && value !== void 0) {
|
|
4
|
+
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
|
|
5
|
+
var dispose, inner;
|
|
6
|
+
if (async) {
|
|
7
|
+
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
|
|
8
|
+
dispose = value[Symbol.asyncDispose];
|
|
9
|
+
}
|
|
10
|
+
if (dispose === void 0) {
|
|
11
|
+
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
|
|
12
|
+
dispose = value[Symbol.dispose];
|
|
13
|
+
if (async) inner = dispose;
|
|
14
|
+
}
|
|
15
|
+
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
|
|
16
|
+
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
|
|
17
|
+
env.stack.push({ value: value, dispose: dispose, async: async });
|
|
18
|
+
}
|
|
19
|
+
else if (async) {
|
|
20
|
+
env.stack.push({ async: true });
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
};
|
|
24
|
+
var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
|
|
25
|
+
return function (env) {
|
|
26
|
+
function fail(e) {
|
|
27
|
+
env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
|
|
28
|
+
env.hasError = true;
|
|
29
|
+
}
|
|
30
|
+
var r, s = 0;
|
|
31
|
+
function next() {
|
|
32
|
+
while (r = env.stack.pop()) {
|
|
33
|
+
try {
|
|
34
|
+
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
|
|
35
|
+
if (r.dispose) {
|
|
36
|
+
var result = r.dispose.call(r.value);
|
|
37
|
+
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
|
|
38
|
+
}
|
|
39
|
+
else s |= 1;
|
|
40
|
+
}
|
|
41
|
+
catch (e) {
|
|
42
|
+
fail(e);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
|
|
46
|
+
if (env.hasError) throw env.error;
|
|
47
|
+
}
|
|
48
|
+
return next();
|
|
49
|
+
};
|
|
50
|
+
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
|
51
|
+
var e = new Error(message);
|
|
52
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
53
|
+
});
|
|
54
|
+
import { Deque } from '@unieai/rabi-deque';
|
|
55
|
+
import { isAppendSurfaceEvent, SessionLogOffset, SessionSeq, } from '@unieai/rabi-session';
|
|
56
|
+
import { SessionQueryError } from '@unieai/rabi-session-query';
|
|
57
|
+
import { RemoteError } from '@unieai/rabi-typert-protocol';
|
|
58
|
+
import { SessionAssistantStreamAccumulator } from "./assistant-stream.js";
|
|
59
|
+
const DEFAULT_MAX_MESSAGES = 50;
|
|
60
|
+
const MESSAGE_TYPES = new Set(['user/message', 'assistant/message']);
|
|
61
|
+
/** Implements cold-safe history operations delegated by the Session Controller. */
|
|
62
|
+
export class SessionHistoryController {
|
|
63
|
+
ctx;
|
|
64
|
+
promote;
|
|
65
|
+
closeFollowers = new Set();
|
|
66
|
+
assistantStreams = new Map();
|
|
67
|
+
/**
|
|
68
|
+
* @param ctx - Host context carrying Session query and projection services.
|
|
69
|
+
* @param promote - starts ordinary Session activation after snapshot delivery.
|
|
70
|
+
*/
|
|
71
|
+
constructor(ctx, promote) {
|
|
72
|
+
this.ctx = ctx;
|
|
73
|
+
this.promote = promote;
|
|
74
|
+
ctx.on('agent/assistant-stream', ({ agent, frame }) => {
|
|
75
|
+
let stream = this.assistantStreams.get(agent.session.id);
|
|
76
|
+
if (stream === undefined) {
|
|
77
|
+
stream = new SessionAssistantStreamAccumulator();
|
|
78
|
+
this.assistantStreams.set(agent.session.id, stream);
|
|
79
|
+
}
|
|
80
|
+
stream.accept(frame, cursorBeforeNext(agent.session.seq));
|
|
81
|
+
}, { global: true });
|
|
82
|
+
ctx.on('agent/disposed', ({ agent }) => {
|
|
83
|
+
this.assistantStreams.delete(agent.session.id);
|
|
84
|
+
}, { global: true });
|
|
85
|
+
ctx.effect(() => () => {
|
|
86
|
+
for (const close of this.closeFollowers)
|
|
87
|
+
close();
|
|
88
|
+
this.closeFollowers.clear();
|
|
89
|
+
}, 'session-controller.history');
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Read one message-aligned history page without activating an Agent.
|
|
93
|
+
* @param request - durable address and backwards-page cursor.
|
|
94
|
+
* @param signal - caller cancellation for persistence reads.
|
|
95
|
+
* @returns a contiguous event page.
|
|
96
|
+
*/
|
|
97
|
+
async page(request, signal) {
|
|
98
|
+
const env_1 = { stack: [], error: void 0, hasError: false };
|
|
99
|
+
try {
|
|
100
|
+
validatePageRequest(request);
|
|
101
|
+
const throughSeq = request.throughSeq === -1
|
|
102
|
+
? -1
|
|
103
|
+
: SessionSeq(request.throughSeq);
|
|
104
|
+
const beforeSeq = request.beforeSeq === undefined
|
|
105
|
+
? undefined
|
|
106
|
+
: SessionLogOffset(request.beforeSeq);
|
|
107
|
+
const source = __addDisposableResource(env_1, await this.sourceFor(request.address, signal, false), false);
|
|
108
|
+
signal.throwIfAborted();
|
|
109
|
+
const sourceLog = source.events;
|
|
110
|
+
const sourceCursor = sourceLog.at(-1)?.seq ?? -1;
|
|
111
|
+
if (throughSeq > sourceCursor) {
|
|
112
|
+
throw new RemoteError('gateway/bad-request', `session page through seq ${String(throughSeq)} is past cursor ${String(sourceCursor)}`, {});
|
|
113
|
+
}
|
|
114
|
+
/* v8 ignore next -- Session and persistence validation guarantee a dense zero-based event prefix. */
|
|
115
|
+
if (throughSeq >= 0 && sourceLog[throughSeq]?.seq !== throughSeq) {
|
|
116
|
+
throw new RemoteError('gateway/internal', `session log does not contain through seq ${String(throughSeq)}`, {});
|
|
117
|
+
}
|
|
118
|
+
const page = paginate(sourceLog, beforeSeq, request.maxMessages ?? DEFAULT_MAX_MESSAGES, throughSeq, request.turnWindow);
|
|
119
|
+
const records = pageRecords(page.events);
|
|
120
|
+
return {
|
|
121
|
+
records,
|
|
122
|
+
hasMore: page.hasMore,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
catch (e_1) {
|
|
126
|
+
env_1.error = e_1;
|
|
127
|
+
env_1.hasError = true;
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
__disposeResources(env_1);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Follow events appended after an initial cursor on one durable address.
|
|
135
|
+
* @param request - durable address and last committed sequence already held by the caller.
|
|
136
|
+
* @param signal - stream cancellation owned by the Remote carrier.
|
|
137
|
+
* @returns a complete opening snapshot followed by gap-free durable events and opted-in assistant frames.
|
|
138
|
+
*/
|
|
139
|
+
async *follow(request, signal) {
|
|
140
|
+
validateHistoryWindow(request);
|
|
141
|
+
const { address } = request;
|
|
142
|
+
const target = addressId(address);
|
|
143
|
+
const buffered = new Deque();
|
|
144
|
+
let snapshotCursor;
|
|
145
|
+
let assistantStreamOrdinal = 0;
|
|
146
|
+
let wake;
|
|
147
|
+
const notify = () => {
|
|
148
|
+
const resume = wake;
|
|
149
|
+
wake = undefined;
|
|
150
|
+
resume?.();
|
|
151
|
+
};
|
|
152
|
+
const follower = { closed: false };
|
|
153
|
+
const close = () => {
|
|
154
|
+
follower.closed = true;
|
|
155
|
+
notify();
|
|
156
|
+
};
|
|
157
|
+
this.closeFollowers.add(close);
|
|
158
|
+
const disposeEvent = this.ctx.on('session/event', (session, event) => {
|
|
159
|
+
if (session.id !== target)
|
|
160
|
+
return;
|
|
161
|
+
buffered.pushBack({ type: 'event', event });
|
|
162
|
+
notify();
|
|
163
|
+
}, { global: true });
|
|
164
|
+
const disposeCreated = this.ctx.on('session/created', (session) => {
|
|
165
|
+
if (session.id !== target)
|
|
166
|
+
return;
|
|
167
|
+
// Constructor seed events have no session/event notification. Normally
|
|
168
|
+
// only the end-seed suffix is new; if persistence advanced after the
|
|
169
|
+
// opening observation, replay everything beyond that snapshot cursor.
|
|
170
|
+
// oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
|
|
171
|
+
const suffix = session.snapshotEvents(snapshotCursor === undefined
|
|
172
|
+
? session.firstLiveSeq
|
|
173
|
+
: SessionLogOffset(snapshotCursor + 1));
|
|
174
|
+
for (let index = suffix.length - 1; index >= 0; index -= 1) {
|
|
175
|
+
buffered.pushFront({ type: 'event', event: suffix[index] });
|
|
176
|
+
}
|
|
177
|
+
notify();
|
|
178
|
+
}, { global: true });
|
|
179
|
+
const disposeAssistantStream = request.assistantStream !== true
|
|
180
|
+
? undefined
|
|
181
|
+
: this.ctx.on('agent/assistant-stream', ({ agent, frame }) => {
|
|
182
|
+
if (agent.session.id !== target)
|
|
183
|
+
return;
|
|
184
|
+
buffered.pushBack({
|
|
185
|
+
type: 'assistant-stream',
|
|
186
|
+
frame: wireAssistantStreamFrame(frame, cursorBeforeNext(agent.session.seq)),
|
|
187
|
+
ordinal: ++assistantStreamOrdinal,
|
|
188
|
+
});
|
|
189
|
+
notify();
|
|
190
|
+
}, { global: true });
|
|
191
|
+
const onAbort = () => { notify(); };
|
|
192
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
193
|
+
try {
|
|
194
|
+
const env_2 = { stack: [], error: void 0, hasError: false };
|
|
195
|
+
try {
|
|
196
|
+
const source = __addDisposableResource(env_2, await this.sourceFor(address, signal, true), false);
|
|
197
|
+
const events = source.events;
|
|
198
|
+
signal.throwIfAborted();
|
|
199
|
+
const cursor = source.cursor;
|
|
200
|
+
snapshotCursor = cursor;
|
|
201
|
+
const page = paginate(events, undefined, request.maxMessages ?? DEFAULT_MAX_MESSAGES, cursor, request.turnWindow);
|
|
202
|
+
const assistantStream = request.assistantStream === true
|
|
203
|
+
? this.assistantStreams.get(target)?.snapshot() ?? { revision: 0 }
|
|
204
|
+
: undefined;
|
|
205
|
+
// The accumulator snapshot and this watermark are synchronous. Frames
|
|
206
|
+
// through the cut are represented or superseded by that baseline,
|
|
207
|
+
// including larger revisions from a retired Agent; later revision
|
|
208
|
+
// resets reach Client continuity validation.
|
|
209
|
+
const assistantStreamOrdinalCut = assistantStreamOrdinal;
|
|
210
|
+
yield {
|
|
211
|
+
type: 'snapshot',
|
|
212
|
+
header: wireHeader(source.header),
|
|
213
|
+
cursor,
|
|
214
|
+
records: pageRecords(page.events),
|
|
215
|
+
hasMore: page.hasMore,
|
|
216
|
+
projections: source.projections === undefined
|
|
217
|
+
? { asOfSeq: cursor, values: {} }
|
|
218
|
+
: projectionBlock(source.projections),
|
|
219
|
+
...assistantStream === undefined ? {} : { assistantStream },
|
|
220
|
+
};
|
|
221
|
+
if (address.kind === 'session' && source.source === 'prepared') {
|
|
222
|
+
const promotion = source.retain();
|
|
223
|
+
try {
|
|
224
|
+
this.promote(promotion);
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
promotion[Symbol.dispose]();
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
let nextOffset = SessionLogOffset(cursor + 1);
|
|
232
|
+
while (!follower.closed && !signal.aborted) {
|
|
233
|
+
const item = buffered.popFront();
|
|
234
|
+
if (item === undefined) {
|
|
235
|
+
await new Promise((resolve) => { wake = resolve; });
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
if (item.type === 'assistant-stream') {
|
|
239
|
+
if (item.ordinal > assistantStreamOrdinalCut) {
|
|
240
|
+
yield { type: 'assistant-stream', frame: item.frame };
|
|
241
|
+
}
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
const expectedSeq = SessionSeq(nextOffset);
|
|
245
|
+
if (item.event.seq < expectedSeq)
|
|
246
|
+
continue;
|
|
247
|
+
if (item.event.seq !== expectedSeq) {
|
|
248
|
+
throw new RemoteError('gateway/internal', `session event stream skipped seq ${String(expectedSeq)}`, {});
|
|
249
|
+
}
|
|
250
|
+
nextOffset = SessionLogOffset(nextOffset + 1);
|
|
251
|
+
yield entryFor(item.event);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
catch (e_2) {
|
|
255
|
+
env_2.error = e_2;
|
|
256
|
+
env_2.hasError = true;
|
|
257
|
+
}
|
|
258
|
+
finally {
|
|
259
|
+
__disposeResources(env_2);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
finally {
|
|
263
|
+
this.closeFollowers.delete(close);
|
|
264
|
+
signal.removeEventListener('abort', onAbort);
|
|
265
|
+
disposeCreated();
|
|
266
|
+
disposeEvent();
|
|
267
|
+
disposeAssistantStream?.();
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
async sourceFor(address, signal, withProjections) {
|
|
271
|
+
const sessionId = addressId(address);
|
|
272
|
+
try {
|
|
273
|
+
const observation = await this.ctx.sessionQuery.observeSession(sessionId, {
|
|
274
|
+
signal,
|
|
275
|
+
projectionMode: withProjections || address.kind === 'subagent' ? 'all' : 'none',
|
|
276
|
+
});
|
|
277
|
+
if (observation.header.cwd === undefined) {
|
|
278
|
+
observation[Symbol.dispose]();
|
|
279
|
+
rejectNotFound(address);
|
|
280
|
+
}
|
|
281
|
+
try {
|
|
282
|
+
validateAddress(address, observation.header, observation.inheritedEventCount, observation.projections);
|
|
283
|
+
}
|
|
284
|
+
catch (error) {
|
|
285
|
+
observation[Symbol.dispose]();
|
|
286
|
+
throw error;
|
|
287
|
+
}
|
|
288
|
+
return observation;
|
|
289
|
+
}
|
|
290
|
+
catch (error) {
|
|
291
|
+
if (error instanceof SessionQueryError
|
|
292
|
+
&& error.code === 'SESSION_QUERY_SESSION_NOT_FOUND')
|
|
293
|
+
rejectNotFound(address);
|
|
294
|
+
throw error;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
function cursorBeforeNext(nextSeq) {
|
|
299
|
+
return nextSeq === 0 ? -1 : SessionSeq(nextSeq - 1);
|
|
300
|
+
}
|
|
301
|
+
function wireAssistantStreamFrame(frame, durableCursor) {
|
|
302
|
+
if (frame.type === 'start')
|
|
303
|
+
return { ...frame, startedAfterSeq: durableCursor };
|
|
304
|
+
if (frame.type === 'end')
|
|
305
|
+
return frame;
|
|
306
|
+
return {
|
|
307
|
+
...frame,
|
|
308
|
+
chunk: frame.chunk,
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
function projectionBlock(snapshot) {
|
|
312
|
+
return {
|
|
313
|
+
asOfSeq: snapshot.asOfSeq,
|
|
314
|
+
// Projection definitions validate whole JSON values before snapshot publication.
|
|
315
|
+
values: snapshot.values,
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
function validatePageRequest(request) {
|
|
319
|
+
if (!Number.isSafeInteger(request.throughSeq)
|
|
320
|
+
|| request.throughSeq < -1
|
|
321
|
+
|| Object.is(request.throughSeq, -0)) {
|
|
322
|
+
throw new RemoteError('gateway/bad-request', 'throughSeq must be an integer greater than or equal to -1', {});
|
|
323
|
+
}
|
|
324
|
+
if (request.beforeSeq !== undefined
|
|
325
|
+
&& (!Number.isSafeInteger(request.beforeSeq)
|
|
326
|
+
|| request.beforeSeq < 0
|
|
327
|
+
|| Object.is(request.beforeSeq, -0))) {
|
|
328
|
+
throw new RemoteError('gateway/bad-request', 'beforeSeq must be a non-negative safe integer', {});
|
|
329
|
+
}
|
|
330
|
+
validateHistoryWindow(request);
|
|
331
|
+
}
|
|
332
|
+
function validateHistoryWindow(request) {
|
|
333
|
+
if (request.maxMessages !== undefined
|
|
334
|
+
&& (!Number.isSafeInteger(request.maxMessages) || request.maxMessages <= 0)) {
|
|
335
|
+
throw new RemoteError('gateway/bad-request', 'maxMessages must be a positive safe integer', {});
|
|
336
|
+
}
|
|
337
|
+
const window = request.turnWindow;
|
|
338
|
+
if (window !== undefined) {
|
|
339
|
+
if (!Number.isSafeInteger(window.minMessages) || window.minMessages <= 0
|
|
340
|
+
|| window.minMessages > (request.maxMessages ?? DEFAULT_MAX_MESSAGES)) {
|
|
341
|
+
throw new RemoteError('gateway/bad-request', 'turnWindow.minMessages must be a positive safe integer no greater than maxMessages', {});
|
|
342
|
+
}
|
|
343
|
+
if (!Number.isSafeInteger(window.minTurns) || window.minTurns <= 0) {
|
|
344
|
+
throw new RemoteError('gateway/bad-request', 'turnWindow.minTurns must be a positive safe integer', {});
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
function addressId(address) {
|
|
349
|
+
return address.kind === 'session' ? address.sessionId : address.childSessionId;
|
|
350
|
+
}
|
|
351
|
+
function validateAddress(address, header, inheritedEventCount, projections) {
|
|
352
|
+
if (address.kind === 'session') {
|
|
353
|
+
if (header.origin === 'subagent') {
|
|
354
|
+
throw new RemoteError('session/agent-busy', 'subagent Sessions require their durable parent address', {
|
|
355
|
+
reason: 'use subagent delivery for this child session',
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
if (header.origin !== 'subagent' || header.parentSession !== address.parentSessionId) {
|
|
361
|
+
throw new RemoteError('subagent/unauthorized', 'subagent does not belong to the supplied parent', {
|
|
362
|
+
childSessionId: address.childSessionId,
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
const identity = projections?.values.subagent;
|
|
366
|
+
if (identity === null) {
|
|
367
|
+
throw new RemoteError('subagent/catalog-diagnostic', 'subagent descriptor is corrupt', {
|
|
368
|
+
parentSessionId: address.parentSessionId,
|
|
369
|
+
childSessionId: address.childSessionId,
|
|
370
|
+
reason: 'corrupt',
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
if (identity === undefined || identity.seq < inheritedEventCount) {
|
|
374
|
+
throw new RemoteError('subagent/catalog-diagnostic', 'subagent descriptor is unavailable', {
|
|
375
|
+
parentSessionId: address.parentSessionId,
|
|
376
|
+
childSessionId: address.childSessionId,
|
|
377
|
+
reason: 'unsupported',
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
if (address.mode !== 'unknown' && identity.mode !== address.mode) {
|
|
381
|
+
throw new RemoteError('subagent/unauthorized', 'subagent mode does not match the supplied address', {
|
|
382
|
+
childSessionId: address.childSessionId,
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
function rejectNotFound(address) {
|
|
387
|
+
if (address.kind === 'session') {
|
|
388
|
+
throw new RemoteError('session/not-found', `session "${address.sessionId}" not found`, { sessionId: address.sessionId });
|
|
389
|
+
}
|
|
390
|
+
throw new RemoteError('subagent/not-found', 'subagent is unavailable', {
|
|
391
|
+
parentSessionId: address.parentSessionId,
|
|
392
|
+
childSessionId: address.childSessionId,
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
function paginate(events, beforeSeq, maxMessages, throughSeq, turnWindow) {
|
|
396
|
+
const end = SessionLogOffset(Math.min(throughSeq + 1, beforeSeq ?? throughSeq + 1));
|
|
397
|
+
let count = 0;
|
|
398
|
+
let turns = 0;
|
|
399
|
+
let cut = SessionLogOffset(0);
|
|
400
|
+
for (let index = end - 1; index >= 0; index--) {
|
|
401
|
+
const event = events[index];
|
|
402
|
+
if (turnWindow !== undefined && event.type === 'turn/start') {
|
|
403
|
+
turns++;
|
|
404
|
+
if (count >= turnWindow.minMessages && turns >= turnWindow.minTurns) {
|
|
405
|
+
cut = SessionLogOffset(index);
|
|
406
|
+
break;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
if (!MESSAGE_TYPES.has(event.type) || !isAppendSurfaceEvent(event))
|
|
410
|
+
continue;
|
|
411
|
+
count++;
|
|
412
|
+
const sources = event.sourceEventSeqs;
|
|
413
|
+
let groupStart = event.seq;
|
|
414
|
+
if (sources !== undefined) {
|
|
415
|
+
for (const source of sources) {
|
|
416
|
+
if (source < groupStart)
|
|
417
|
+
groupStart = source;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
if (count >= maxMessages) {
|
|
421
|
+
cut = SessionLogOffset(groupStart);
|
|
422
|
+
break;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
return { events: events.slice(cut, end), hasMore: cut > 0 };
|
|
426
|
+
}
|
|
427
|
+
/** Translate current logical Session metadata to the browser wire. */
|
|
428
|
+
function wireHeader(header) {
|
|
429
|
+
return { ...header };
|
|
430
|
+
}
|
|
431
|
+
function entryFor(event) {
|
|
432
|
+
return {
|
|
433
|
+
type: 'event',
|
|
434
|
+
// Session.append validates and freezes event data as JSON before publication.
|
|
435
|
+
event: event,
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
/** Encode one bounded logical page without changing its pagination cut. */
|
|
439
|
+
function pageRecords(events) {
|
|
440
|
+
return events.map(entryFor);
|
|
441
|
+
}
|