@schlessera/brain-ui-server 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/dist/agent/backend.d.ts.map +1 -1
- package/dist/agent/backend.js +6 -2
- package/dist/agent/backend.js.map +1 -1
- package/dist/app.d.ts +9 -0
- package/dist/app.d.ts.map +1 -1
- package/dist/app.js +37 -6
- package/dist/app.js.map +1 -1
- package/dist/config/env.d.ts +8 -0
- package/dist/config/env.d.ts.map +1 -1
- package/dist/config/env.js +48 -0
- package/dist/config/env.js.map +1 -1
- package/dist/cron/scheduler.d.ts +3 -0
- package/dist/cron/scheduler.d.ts.map +1 -1
- package/dist/cron/scheduler.js +11 -3
- package/dist/cron/scheduler.js.map +1 -1
- package/dist/db/client.d.ts +10 -1
- package/dist/db/client.d.ts.map +1 -1
- package/dist/db/client.js +5 -14
- package/dist/db/client.js.map +1 -1
- package/dist/db/settings.d.ts +2 -1
- package/dist/db/settings.d.ts.map +1 -1
- package/dist/db/settings.js +6 -2
- package/dist/db/settings.js.map +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -2
- package/dist/index.js.map +1 -1
- package/dist/middleware/auth.d.ts +3 -2
- package/dist/middleware/auth.d.ts.map +1 -1
- package/dist/middleware/auth.js +28 -9
- package/dist/middleware/auth.js.map +1 -1
- package/dist/middleware/passkeys.d.ts +10 -0
- package/dist/middleware/passkeys.d.ts.map +1 -1
- package/dist/middleware/passkeys.js +19 -3
- package/dist/middleware/passkeys.js.map +1 -1
- package/dist/observability/index.d.ts +73 -0
- package/dist/observability/index.d.ts.map +1 -0
- package/dist/observability/index.js +74 -0
- package/dist/observability/index.js.map +1 -0
- package/dist/observability/loggers.d.ts +62 -0
- package/dist/observability/loggers.d.ts.map +1 -0
- package/dist/observability/loggers.js +109 -0
- package/dist/observability/loggers.js.map +1 -0
- package/dist/observability/meter.d.ts +39 -0
- package/dist/observability/meter.d.ts.map +1 -0
- package/dist/observability/meter.js +95 -0
- package/dist/observability/meter.js.map +1 -0
- package/dist/observability/types.d.ts +67 -0
- package/dist/observability/types.d.ts.map +1 -0
- package/dist/observability/types.js +44 -0
- package/dist/observability/types.js.map +1 -0
- package/dist/routes/brain.d.ts.map +1 -1
- package/dist/routes/brain.js +9 -1
- package/dist/routes/brain.js.map +1 -1
- package/dist/routes/files.d.ts +2 -0
- package/dist/routes/files.d.ts.map +1 -1
- package/dist/routes/files.js +7 -7
- package/dist/routes/files.js.map +1 -1
- package/dist/routes/graph.d.ts +2 -0
- package/dist/routes/graph.d.ts.map +1 -1
- package/dist/routes/graph.js +7 -7
- package/dist/routes/graph.js.map +1 -1
- package/dist/routes/health.d.ts +3 -0
- package/dist/routes/health.d.ts.map +1 -1
- package/dist/routes/health.js +3 -0
- package/dist/routes/health.js.map +1 -1
- package/dist/routes/models.d.ts +3 -0
- package/dist/routes/models.d.ts.map +1 -1
- package/dist/routes/models.js +5 -1
- package/dist/routes/models.js.map +1 -1
- package/dist/routes/render.d.ts +2 -1
- package/dist/routes/render.d.ts.map +1 -1
- package/dist/routes/render.js +2 -2
- package/dist/routes/render.js.map +1 -1
- package/dist/routes/share.d.ts +3 -0
- package/dist/routes/share.d.ts.map +1 -1
- package/dist/routes/share.js +3 -3
- package/dist/routes/share.js.map +1 -1
- package/dist/share/staging.d.ts +3 -2
- package/dist/share/staging.d.ts.map +1 -1
- package/dist/share/staging.js +12 -4
- package/dist/share/staging.js.map +1 -1
- package/dist/voice/keyterm-builder.d.ts +4 -1
- package/dist/voice/keyterm-builder.d.ts.map +1 -1
- package/dist/voice/keyterm-builder.js +13 -6
- package/dist/voice/keyterm-builder.js.map +1 -1
- package/dist/ws/bridge.d.ts.map +1 -1
- package/dist/ws/bridge.js +6 -1
- package/dist/ws/bridge.js.map +1 -1
- package/dist/ws/connection.d.ts +15 -0
- package/dist/ws/connection.d.ts.map +1 -1
- package/dist/ws/connection.js +55 -8
- package/dist/ws/connection.js.map +1 -1
- package/dist/ws/dispatch.d.ts +22 -1
- package/dist/ws/dispatch.d.ts.map +1 -1
- package/dist/ws/dispatch.js +33 -15
- package/dist/ws/dispatch.js.map +1 -1
- package/dist/ws/host.d.ts +37 -0
- package/dist/ws/host.d.ts.map +1 -1
- package/dist/ws/host.js +37 -0
- package/dist/ws/host.js.map +1 -1
- package/dist/ws/rate-limit.d.ts +58 -0
- package/dist/ws/rate-limit.d.ts.map +1 -0
- package/dist/ws/rate-limit.js +62 -0
- package/dist/ws/rate-limit.js.map +1 -0
- package/dist/ws/run-session.d.ts +3 -0
- package/dist/ws/run-session.d.ts.map +1 -1
- package/dist/ws/run-session.js +23 -5
- package/dist/ws/run-session.js.map +1 -1
- package/dist/ws/turns.d.ts +13 -0
- package/dist/ws/turns.d.ts.map +1 -1
- package/dist/ws/turns.js +11 -1
- package/dist/ws/turns.js.map +1 -1
- package/package.json +5 -3
- package/src/agent/backend.ts +8 -6
- package/src/app.ts +46 -6
- package/src/config/env.ts +57 -0
- package/src/cron/scheduler.ts +14 -3
- package/src/db/client.ts +16 -5
- package/src/db/settings.ts +7 -2
- package/src/index.ts +37 -2
- package/src/middleware/auth.ts +30 -14
- package/src/middleware/passkeys.ts +29 -5
- package/src/observability/index.ts +150 -0
- package/src/observability/loggers.ts +174 -0
- package/src/observability/meter.ts +190 -0
- package/src/observability/types.ts +101 -0
- package/src/routes/brain.ts +10 -1
- package/src/routes/files.ts +9 -8
- package/src/routes/graph.ts +9 -8
- package/src/routes/health.ts +7 -0
- package/src/routes/models.ts +8 -5
- package/src/routes/render.ts +3 -2
- package/src/routes/share.ts +6 -3
- package/src/share/staging.ts +18 -4
- package/src/voice/keyterm-builder.ts +17 -8
- package/src/ws/bridge.ts +5 -1
- package/src/ws/connection.ts +63 -12
- package/src/ws/dispatch.ts +44 -15
- package/src/ws/host.ts +54 -0
- package/src/ws/rate-limit.ts +86 -0
- package/src/ws/run-session.ts +26 -7
- package/src/ws/turns.ts +19 -3
package/src/ws/dispatch.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PROTOCOL_REV_CLIENT_ECHO } from "@schlessera/brain-ui-sdk/protocol";
|
|
1
2
|
import type { ClientMessage } from "@schlessera/brain-ui-sdk/protocol";
|
|
2
3
|
import type { WSContext } from "./clients.js";
|
|
3
4
|
import { locationErrorText } from "./frames.js";
|
|
@@ -6,23 +7,51 @@ import { validateAttachments } from "./attachments.js";
|
|
|
6
7
|
import { handleChatMessage } from "./run-session.js";
|
|
7
8
|
import type { WsHost } from "./host.js";
|
|
8
9
|
|
|
10
|
+
/** Per-connection negotiation state, owned by the socket handler. */
|
|
11
|
+
export interface ConnectionState {
|
|
12
|
+
/** Revision the client declared via `client_hello`; absent means rev 2. */
|
|
13
|
+
protocolRev?: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
9
16
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* a
|
|
13
|
-
*
|
|
17
|
+
* Does this reply's echoed turnId identify the turn that raised the request?
|
|
18
|
+
*
|
|
19
|
+
* A wrong id is always refused: a stale echo from before a reconnect or a
|
|
20
|
+
* follow-up would resolve a different turn's pending promise.
|
|
21
|
+
*
|
|
22
|
+
* A MISSING id depends on who is speaking. A client that declared rev 3
|
|
23
|
+
* promised to echo, so silence means the reply cannot be correlated and is
|
|
24
|
+
* refused. A client that declared nothing is rev 2, where the field is
|
|
25
|
+
* optional, and is still tolerated — that tolerance is the deprecation window,
|
|
26
|
+
* and it is what lets this be enforced at all without breaking clients that
|
|
27
|
+
* predate `client_hello`.
|
|
14
28
|
*/
|
|
15
|
-
function turnIdMatches(
|
|
16
|
-
|
|
29
|
+
export function turnIdMatches(
|
|
30
|
+
pending: { turnId: string },
|
|
31
|
+
echoed: string | undefined,
|
|
32
|
+
requireEcho: boolean
|
|
33
|
+
): boolean {
|
|
34
|
+
if (echoed === undefined) return !requireEcho;
|
|
35
|
+
return echoed === pending.turnId;
|
|
17
36
|
}
|
|
18
37
|
|
|
19
38
|
export async function handleClientMessage(
|
|
20
39
|
host: WsHost,
|
|
21
40
|
ws: WSContext,
|
|
22
|
-
msg: ClientMessage
|
|
41
|
+
msg: ClientMessage,
|
|
42
|
+
connection: ConnectionState = {}
|
|
23
43
|
): Promise<void> {
|
|
24
44
|
const { coordinator, catalog } = host;
|
|
45
|
+
const requireEcho = (connection.protocolRev ?? 2) >= PROTOCOL_REV_CLIENT_ECHO;
|
|
25
46
|
switch (msg.type) {
|
|
47
|
+
case "client_hello": {
|
|
48
|
+
// Record what this connection speaks. Never rejected on version: a
|
|
49
|
+
// future client declaring rev 9 is simply held to the rules this host
|
|
50
|
+
// knows, and an unknown capability flag is ignored.
|
|
51
|
+
connection.protocolRev = msg.protocolRev;
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
|
|
26
55
|
case "chat_message": {
|
|
27
56
|
const attachmentResult = validateAttachments(msg.attachments);
|
|
28
57
|
if (!attachmentResult.ok) {
|
|
@@ -46,7 +75,7 @@ export async function handleClientMessage(
|
|
|
46
75
|
|
|
47
76
|
case "ask_user_response": {
|
|
48
77
|
const pending = coordinator.pendingAskUser.get(msg.requestId);
|
|
49
|
-
if (pending && turnIdMatches(pending, msg.turnId)) {
|
|
78
|
+
if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) {
|
|
50
79
|
coordinator.pendingAskUser.delete(msg.requestId);
|
|
51
80
|
pending.resolve({ answers: msg.answers, annotations: msg.annotations });
|
|
52
81
|
}
|
|
@@ -55,7 +84,7 @@ export async function handleClientMessage(
|
|
|
55
84
|
|
|
56
85
|
case "ask_user_cancel": {
|
|
57
86
|
const pending = coordinator.pendingAskUser.get(msg.requestId);
|
|
58
|
-
if (pending && turnIdMatches(pending, msg.turnId)) {
|
|
87
|
+
if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) {
|
|
59
88
|
coordinator.pendingAskUser.delete(msg.requestId);
|
|
60
89
|
pending.reject(new Error(msg.reason || "User cancelled the question"));
|
|
61
90
|
}
|
|
@@ -64,7 +93,7 @@ export async function handleClientMessage(
|
|
|
64
93
|
|
|
65
94
|
case "location_response": {
|
|
66
95
|
const pending = coordinator.pendingLocation.get(msg.requestId);
|
|
67
|
-
if (pending && turnIdMatches(pending, msg.turnId)) {
|
|
96
|
+
if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) {
|
|
68
97
|
coordinator.pendingLocation.delete(msg.requestId);
|
|
69
98
|
pending.resolve({ coords: msg.coords, timestamp: msg.timestamp });
|
|
70
99
|
}
|
|
@@ -73,7 +102,7 @@ export async function handleClientMessage(
|
|
|
73
102
|
|
|
74
103
|
case "location_error": {
|
|
75
104
|
const pending = coordinator.pendingLocation.get(msg.requestId);
|
|
76
|
-
if (pending && turnIdMatches(pending, msg.turnId)) {
|
|
105
|
+
if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) {
|
|
77
106
|
coordinator.pendingLocation.delete(msg.requestId);
|
|
78
107
|
pending.reject(new Error(locationErrorText(msg.code, msg.message)));
|
|
79
108
|
}
|
|
@@ -82,7 +111,7 @@ export async function handleClientMessage(
|
|
|
82
111
|
|
|
83
112
|
case "mask_response": {
|
|
84
113
|
const pending = coordinator.pendingMask.get(msg.requestId);
|
|
85
|
-
if (pending && turnIdMatches(pending, msg.turnId)) {
|
|
114
|
+
if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) {
|
|
86
115
|
coordinator.pendingMask.delete(msg.requestId);
|
|
87
116
|
// Decoded here rather than in the tool: the boundary already validated
|
|
88
117
|
// the base64 and its size, so the backend gets bytes it can trust.
|
|
@@ -93,7 +122,7 @@ export async function handleClientMessage(
|
|
|
93
122
|
|
|
94
123
|
case "mask_error": {
|
|
95
124
|
const pending = coordinator.pendingMask.get(msg.requestId);
|
|
96
|
-
if (pending && turnIdMatches(pending, msg.turnId)) {
|
|
125
|
+
if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) {
|
|
97
126
|
coordinator.pendingMask.delete(msg.requestId);
|
|
98
127
|
pending.reject(
|
|
99
128
|
new Error(
|
|
@@ -108,7 +137,7 @@ export async function handleClientMessage(
|
|
|
108
137
|
|
|
109
138
|
case "tool_approval": {
|
|
110
139
|
const pending = coordinator.pendingApprovals.get(msg.toolUseId);
|
|
111
|
-
if (pending && turnIdMatches(pending, msg.turnId)) {
|
|
140
|
+
if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) {
|
|
112
141
|
coordinator.pendingApprovals.delete(msg.toolUseId);
|
|
113
142
|
pending.resolve(
|
|
114
143
|
msg.updatedInput
|
|
@@ -121,7 +150,7 @@ export async function handleClientMessage(
|
|
|
121
150
|
|
|
122
151
|
case "tool_denial": {
|
|
123
152
|
const pending = coordinator.pendingApprovals.get(msg.toolUseId);
|
|
124
|
-
if (pending && turnIdMatches(pending, msg.turnId)) {
|
|
153
|
+
if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) {
|
|
125
154
|
coordinator.pendingApprovals.delete(msg.toolUseId);
|
|
126
155
|
pending.resolve({ behavior: "deny", message: msg.message });
|
|
127
156
|
}
|
package/src/ws/host.ts
CHANGED
|
@@ -3,6 +3,8 @@ import { ClientSet, sendTo, type WSContext } from "./clients.js";
|
|
|
3
3
|
import { TurnCoordinator } from "./turns.js";
|
|
4
4
|
import type { SessionCatalog } from "./session-catalog.js";
|
|
5
5
|
import type { BackendRegistry } from "../agent/backend.js";
|
|
6
|
+
import { createSilentObservability, type Observability } from "../observability/index.js";
|
|
7
|
+
import { FrameRateLimiter } from "./rate-limit.js";
|
|
6
8
|
|
|
7
9
|
/** Host-side turn timeout. The backend no longer times out — the host owns it. */
|
|
8
10
|
const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes
|
|
@@ -50,6 +52,19 @@ export interface WsHostOptions {
|
|
|
50
52
|
* it dynamic; createApp passes the resolved config value.
|
|
51
53
|
*/
|
|
52
54
|
maxConcurrentSessions?: () => number;
|
|
55
|
+
/**
|
|
56
|
+
* Where this coordinator reports. Injected rather than reached for, so two
|
|
57
|
+
* apps in one process report separately and a test can assert on what the
|
|
58
|
+
* socket layer actually said. Defaults to silence: an embedder that never
|
|
59
|
+
* passes one gets no output, not a surprise stream on stdout.
|
|
60
|
+
*/
|
|
61
|
+
observability?: Observability;
|
|
62
|
+
/**
|
|
63
|
+
* Inbound frame metering policy, per connection. Omitted (or a rate of 0)
|
|
64
|
+
* means no metering — which is what a test wants, and what an embedder
|
|
65
|
+
* fronting the socket with its own limiter wants.
|
|
66
|
+
*/
|
|
67
|
+
wsRate?: { ratePerSecond: number; burst: number };
|
|
53
68
|
}
|
|
54
69
|
|
|
55
70
|
/**
|
|
@@ -66,6 +81,13 @@ export class WsHost {
|
|
|
66
81
|
appName: string;
|
|
67
82
|
turnTimeoutMs: number;
|
|
68
83
|
maxConcurrentSessions: () => number;
|
|
84
|
+
readonly observability: Observability;
|
|
85
|
+
readonly wsRate: { ratePerSecond: number; burst: number } | null;
|
|
86
|
+
/** Scoped instruments, resolved once — `[ws]` is the existing log prefix. */
|
|
87
|
+
readonly log: ReturnType<Observability["logger"]>;
|
|
88
|
+
private readonly framesDropped: ReturnType<
|
|
89
|
+
ReturnType<Observability["meter"]>["createCounter"]
|
|
90
|
+
>;
|
|
69
91
|
|
|
70
92
|
constructor(options: WsHostOptions) {
|
|
71
93
|
this.registry = options.registry;
|
|
@@ -74,6 +96,38 @@ export class WsHost {
|
|
|
74
96
|
this.turnTimeoutMs = options.turnTimeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
75
97
|
this.maxConcurrentSessions =
|
|
76
98
|
options.maxConcurrentSessions ?? (() => DEFAULT_MAX_CONCURRENT_SESSIONS);
|
|
99
|
+
this.observability = options.observability ?? createSilentObservability();
|
|
100
|
+
this.wsRate =
|
|
101
|
+
options.wsRate && options.wsRate.ratePerSecond > 0 ? options.wsRate : null;
|
|
102
|
+
this.log = this.observability.logger("ws");
|
|
103
|
+
this.framesDropped = this.observability
|
|
104
|
+
.meter("ws")
|
|
105
|
+
.createCounter("ws.frames.dropped", {
|
|
106
|
+
description: "Inbound frames refused before reaching a handler",
|
|
107
|
+
});
|
|
108
|
+
this.coordinator.log = this.log;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** A metering bucket for one new connection, or null when metering is off. */
|
|
112
|
+
newRateLimiter(): FrameRateLimiter | null {
|
|
113
|
+
return this.wsRate ? new FrameRateLimiter(this.wsRate) : null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Record a frame this server refused, and say so.
|
|
118
|
+
*
|
|
119
|
+
* Before this existed, every rejection answered the client and vanished:
|
|
120
|
+
* `parseClientMessage` failures were never logged, so the validation we
|
|
121
|
+
* already shipped had no observability at all. `reason` is a bounded token,
|
|
122
|
+
* never the frame body — the payload is caller-supplied and can be 12 MB.
|
|
123
|
+
*/
|
|
124
|
+
reportDroppedFrame(reason: string, detail?: string): void {
|
|
125
|
+
this.framesDropped.add(1, { reason, direction: "inbound" });
|
|
126
|
+
this.log.emit({
|
|
127
|
+
severityText: "WARN",
|
|
128
|
+
body: "inbound frame rejected",
|
|
129
|
+
attributes: detail ? { reason, detail } : { reason },
|
|
130
|
+
});
|
|
77
131
|
}
|
|
78
132
|
|
|
79
133
|
/** Fan a frame out to every attached client (size-bounded per frame). */
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-connection inbound frame metering.
|
|
3
|
+
*
|
|
4
|
+
* Frames are already size-, cardinality- and depth-bounded, so the cheap CPU
|
|
5
|
+
* amplification is closed. What was left unmetered is VOLUME: a flood of
|
|
6
|
+
* individually valid frames behind the auth guard. That is a smaller threat
|
|
7
|
+
* than an unauthenticated one — it needs a session — but "the attacker had to
|
|
8
|
+
* log in first" is not a bound.
|
|
9
|
+
*
|
|
10
|
+
* A token bucket rather than a fixed window, because the traffic this protects
|
|
11
|
+
* is bursty by nature and a fixed window punishes the wrong thing. Opening the
|
|
12
|
+
* app fires a handful of frames at once (resume, environment, a first
|
|
13
|
+
* message); an approval storm during a busy turn is a dozen in a second. Both
|
|
14
|
+
* are legitimate and both fit in the burst. What does not fit is a sustained
|
|
15
|
+
* rate no human produces.
|
|
16
|
+
*
|
|
17
|
+
* Inbound traffic is naturally low-rate — deltas flow the other way — so the
|
|
18
|
+
* defaults are generous enough that no real client should ever see one of
|
|
19
|
+
* these, which is the property that makes it safe to turn on by default.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** Injected so tests need no real time. */
|
|
23
|
+
export interface Clock {
|
|
24
|
+
now(): number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const realClock: Clock = { now: () => Date.now() };
|
|
28
|
+
|
|
29
|
+
export interface RateLimitOptions {
|
|
30
|
+
/** Sustained frames per second. */
|
|
31
|
+
ratePerSecond: number;
|
|
32
|
+
/** Frames absorbable in one burst before the sustained rate applies. */
|
|
33
|
+
burst: number;
|
|
34
|
+
clock?: Clock;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface RateLimitDecision {
|
|
38
|
+
allowed: boolean;
|
|
39
|
+
/** Tokens left after this decision, for reporting. */
|
|
40
|
+
remaining: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* One bucket per connection. Not shared, and not keyed by anything
|
|
45
|
+
* user-supplied: a map keyed by session or IP is itself an unbounded
|
|
46
|
+
* allocation an attacker controls, which is the classic way a rate limiter
|
|
47
|
+
* becomes the memory-exhaustion bug it was added to prevent. This lives on the
|
|
48
|
+
* socket and dies with it.
|
|
49
|
+
*/
|
|
50
|
+
export class FrameRateLimiter {
|
|
51
|
+
private tokens: number;
|
|
52
|
+
private lastRefill: number;
|
|
53
|
+
private readonly ratePerMs: number;
|
|
54
|
+
private readonly burst: number;
|
|
55
|
+
private readonly clock: Clock;
|
|
56
|
+
/** Frames refused since the connection opened. */
|
|
57
|
+
private rejected = 0;
|
|
58
|
+
|
|
59
|
+
constructor(options: RateLimitOptions) {
|
|
60
|
+
this.burst = Math.max(1, options.burst);
|
|
61
|
+
this.ratePerMs = Math.max(0, options.ratePerSecond) / 1000;
|
|
62
|
+
this.clock = options.clock ?? realClock;
|
|
63
|
+
this.tokens = this.burst;
|
|
64
|
+
this.lastRefill = this.clock.now();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Take one token. False means this frame should be refused. */
|
|
68
|
+
take(): RateLimitDecision {
|
|
69
|
+
const now = this.clock.now();
|
|
70
|
+
const elapsed = Math.max(0, now - this.lastRefill);
|
|
71
|
+
this.lastRefill = now;
|
|
72
|
+
this.tokens = Math.min(this.burst, this.tokens + elapsed * this.ratePerMs);
|
|
73
|
+
|
|
74
|
+
if (this.tokens < 1) {
|
|
75
|
+
this.rejected++;
|
|
76
|
+
return { allowed: false, remaining: 0 };
|
|
77
|
+
}
|
|
78
|
+
this.tokens -= 1;
|
|
79
|
+
return { allowed: true, remaining: Math.floor(this.tokens) };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** How many frames this connection has had refused. */
|
|
83
|
+
get rejectedCount(): number {
|
|
84
|
+
return this.rejected;
|
|
85
|
+
}
|
|
86
|
+
}
|
package/src/ws/run-session.ts
CHANGED
|
@@ -20,6 +20,8 @@ export async function runSession(
|
|
|
20
20
|
attachments: ChatImageAttachment[];
|
|
21
21
|
providerId?: string;
|
|
22
22
|
client?: ClientEnvironment;
|
|
23
|
+
/** Client correlation id for a new conversation; echoed on session_info. */
|
|
24
|
+
draftId?: string;
|
|
23
25
|
}
|
|
24
26
|
): Promise<void> {
|
|
25
27
|
const { coordinator } = host;
|
|
@@ -41,10 +43,11 @@ export async function runSession(
|
|
|
41
43
|
|
|
42
44
|
const { backend, profileId: initialProfileId } = target;
|
|
43
45
|
if (target.droppedPin) {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
46
|
+
host.log.emit({
|
|
47
|
+
severityText: "WARN",
|
|
48
|
+
body: "pinned profile unavailable; running on the default profile",
|
|
49
|
+
attributes: { "session.id": initial.sessionId, profile: target.droppedPin },
|
|
50
|
+
});
|
|
48
51
|
host.sendToClients({
|
|
49
52
|
type: "status",
|
|
50
53
|
status: "thinking",
|
|
@@ -55,6 +58,8 @@ export async function runSession(
|
|
|
55
58
|
const turn: RunningTurn = {
|
|
56
59
|
sessionId: initial.sessionId ?? null,
|
|
57
60
|
turnId: crypto.randomUUID(),
|
|
61
|
+
// Only meaningful when the client had no session id to send.
|
|
62
|
+
draftId: initial.sessionId ? null : (initial.draftId ?? null),
|
|
58
63
|
providerId: initialProfileId ?? null,
|
|
59
64
|
backend,
|
|
60
65
|
abortController: new AbortController(),
|
|
@@ -82,7 +87,11 @@ export async function runSession(
|
|
|
82
87
|
const abortController = new AbortController();
|
|
83
88
|
turn.abortController = abortController;
|
|
84
89
|
const timeoutHandle = setTimeout(() => {
|
|
85
|
-
|
|
90
|
+
host.log.emit({
|
|
91
|
+
severityText: "WARN",
|
|
92
|
+
body: "turn timed out",
|
|
93
|
+
attributes: { "timeout.ms": host.turnTimeoutMs },
|
|
94
|
+
});
|
|
86
95
|
abortController.abort();
|
|
87
96
|
// Reject any pending interactive request for this turn too. A bridge
|
|
88
97
|
// that awaits askUser/approval without racing the abort signal would
|
|
@@ -144,9 +153,10 @@ export async function handleChatMessage(
|
|
|
144
153
|
attachments: ChatImageAttachment[];
|
|
145
154
|
providerId?: string;
|
|
146
155
|
client?: ClientEnvironment;
|
|
156
|
+
draftId?: string;
|
|
147
157
|
}
|
|
148
158
|
): Promise<void> {
|
|
149
|
-
const { text, attachments, sessionId, providerId: requestedProviderId, client } = msg;
|
|
159
|
+
const { text, attachments, sessionId, providerId: requestedProviderId, client, draftId } = msg;
|
|
150
160
|
const { coordinator } = host;
|
|
151
161
|
const runningTurn = sessionId ? coordinator.bySession.get(sessionId) : undefined;
|
|
152
162
|
|
|
@@ -204,7 +214,15 @@ export async function handleChatMessage(
|
|
|
204
214
|
? `Queue is holding ${formatMb(total)} across ${runningTurn.queue.length} messages (limit ${formatMb(QUEUE_MAX_BYTES)}).`
|
|
205
215
|
: undefined;
|
|
206
216
|
if (detail) {
|
|
207
|
-
|
|
217
|
+
host.log.emit({
|
|
218
|
+
severityText: "WARN",
|
|
219
|
+
body: "session follow-up queue is heavy",
|
|
220
|
+
attributes: {
|
|
221
|
+
"session.id": sessionId,
|
|
222
|
+
size: formatMb(total),
|
|
223
|
+
queued: runningTurn.queue.length,
|
|
224
|
+
},
|
|
225
|
+
});
|
|
208
226
|
}
|
|
209
227
|
host.sendToClients(
|
|
210
228
|
withSessionId({ type: "status", status: "queued", ...(detail ? { detail } : {}) }, sessionId)
|
|
@@ -234,5 +252,6 @@ export async function handleChatMessage(
|
|
|
234
252
|
attachments,
|
|
235
253
|
providerId: requestedProviderId,
|
|
236
254
|
...(client ? { client } : {}),
|
|
255
|
+
...(draftId ? { draftId } : {}),
|
|
237
256
|
});
|
|
238
257
|
}
|
package/src/ws/turns.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Logger } from "@opentelemetry/api-logs";
|
|
1
2
|
import type {
|
|
2
3
|
AgentBackend,
|
|
3
4
|
PermissionDecision,
|
|
@@ -54,6 +55,12 @@ export interface RunningTurn {
|
|
|
54
55
|
timeoutHandle: ReturnType<typeof setTimeout>;
|
|
55
56
|
queue: QueuedFollowUp[];
|
|
56
57
|
cancelled: boolean;
|
|
58
|
+
/**
|
|
59
|
+
* Correlation id the client minted for this NEW conversation, echoed back on
|
|
60
|
+
* `session_info` so the client can tell its own turn's identity from a
|
|
61
|
+
* background turn's. Null on a resumed session or a client that sent none.
|
|
62
|
+
*/
|
|
63
|
+
draftId: string | null;
|
|
57
64
|
}
|
|
58
65
|
|
|
59
66
|
// Pending interactive requests are tagged with their turn so a per-session
|
|
@@ -93,6 +100,13 @@ export interface PendingMask {
|
|
|
93
100
|
* explicit object with a defined lifecycle.
|
|
94
101
|
*/
|
|
95
102
|
export class TurnCoordinator {
|
|
103
|
+
/**
|
|
104
|
+
* Where collisions are reported. Assigned by the owning WsHost so the
|
|
105
|
+
* coordinator reports through the same consumer as everything else; absent
|
|
106
|
+
* (a bare coordinator in a test) means silence.
|
|
107
|
+
*/
|
|
108
|
+
log?: Logger;
|
|
109
|
+
|
|
96
110
|
readonly running = new Set<RunningTurn>();
|
|
97
111
|
readonly bySession = new Map<string, RunningTurn>();
|
|
98
112
|
startingSessions = 0;
|
|
@@ -173,9 +187,11 @@ export class TurnCoordinator {
|
|
|
173
187
|
): boolean {
|
|
174
188
|
const existing = map.get(id);
|
|
175
189
|
if (existing && existing.turn !== turn) {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
190
|
+
this.log?.emit({
|
|
191
|
+
severityText: "ERROR",
|
|
192
|
+
body: "interactive id collision: already pending for another turn",
|
|
193
|
+
attributes: { "request.id": id },
|
|
194
|
+
});
|
|
179
195
|
return true;
|
|
180
196
|
}
|
|
181
197
|
return false;
|