@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.
Files changed (144) hide show
  1. package/README.md +3 -0
  2. package/dist/agent/backend.d.ts.map +1 -1
  3. package/dist/agent/backend.js +6 -2
  4. package/dist/agent/backend.js.map +1 -1
  5. package/dist/app.d.ts +9 -0
  6. package/dist/app.d.ts.map +1 -1
  7. package/dist/app.js +37 -6
  8. package/dist/app.js.map +1 -1
  9. package/dist/config/env.d.ts +8 -0
  10. package/dist/config/env.d.ts.map +1 -1
  11. package/dist/config/env.js +48 -0
  12. package/dist/config/env.js.map +1 -1
  13. package/dist/cron/scheduler.d.ts +3 -0
  14. package/dist/cron/scheduler.d.ts.map +1 -1
  15. package/dist/cron/scheduler.js +11 -3
  16. package/dist/cron/scheduler.js.map +1 -1
  17. package/dist/db/client.d.ts +10 -1
  18. package/dist/db/client.d.ts.map +1 -1
  19. package/dist/db/client.js +5 -14
  20. package/dist/db/client.js.map +1 -1
  21. package/dist/db/settings.d.ts +2 -1
  22. package/dist/db/settings.d.ts.map +1 -1
  23. package/dist/db/settings.js +6 -2
  24. package/dist/db/settings.js.map +1 -1
  25. package/dist/index.d.ts +4 -2
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +6 -2
  28. package/dist/index.js.map +1 -1
  29. package/dist/middleware/auth.d.ts +3 -2
  30. package/dist/middleware/auth.d.ts.map +1 -1
  31. package/dist/middleware/auth.js +28 -9
  32. package/dist/middleware/auth.js.map +1 -1
  33. package/dist/middleware/passkeys.d.ts +10 -0
  34. package/dist/middleware/passkeys.d.ts.map +1 -1
  35. package/dist/middleware/passkeys.js +19 -3
  36. package/dist/middleware/passkeys.js.map +1 -1
  37. package/dist/observability/index.d.ts +73 -0
  38. package/dist/observability/index.d.ts.map +1 -0
  39. package/dist/observability/index.js +74 -0
  40. package/dist/observability/index.js.map +1 -0
  41. package/dist/observability/loggers.d.ts +62 -0
  42. package/dist/observability/loggers.d.ts.map +1 -0
  43. package/dist/observability/loggers.js +109 -0
  44. package/dist/observability/loggers.js.map +1 -0
  45. package/dist/observability/meter.d.ts +39 -0
  46. package/dist/observability/meter.d.ts.map +1 -0
  47. package/dist/observability/meter.js +95 -0
  48. package/dist/observability/meter.js.map +1 -0
  49. package/dist/observability/types.d.ts +67 -0
  50. package/dist/observability/types.d.ts.map +1 -0
  51. package/dist/observability/types.js +44 -0
  52. package/dist/observability/types.js.map +1 -0
  53. package/dist/routes/brain.d.ts.map +1 -1
  54. package/dist/routes/brain.js +9 -1
  55. package/dist/routes/brain.js.map +1 -1
  56. package/dist/routes/files.d.ts +2 -0
  57. package/dist/routes/files.d.ts.map +1 -1
  58. package/dist/routes/files.js +7 -7
  59. package/dist/routes/files.js.map +1 -1
  60. package/dist/routes/graph.d.ts +2 -0
  61. package/dist/routes/graph.d.ts.map +1 -1
  62. package/dist/routes/graph.js +7 -7
  63. package/dist/routes/graph.js.map +1 -1
  64. package/dist/routes/health.d.ts +3 -0
  65. package/dist/routes/health.d.ts.map +1 -1
  66. package/dist/routes/health.js +3 -0
  67. package/dist/routes/health.js.map +1 -1
  68. package/dist/routes/models.d.ts +3 -0
  69. package/dist/routes/models.d.ts.map +1 -1
  70. package/dist/routes/models.js +5 -1
  71. package/dist/routes/models.js.map +1 -1
  72. package/dist/routes/render.d.ts +2 -1
  73. package/dist/routes/render.d.ts.map +1 -1
  74. package/dist/routes/render.js +2 -2
  75. package/dist/routes/render.js.map +1 -1
  76. package/dist/routes/share.d.ts +3 -0
  77. package/dist/routes/share.d.ts.map +1 -1
  78. package/dist/routes/share.js +3 -3
  79. package/dist/routes/share.js.map +1 -1
  80. package/dist/share/staging.d.ts +3 -2
  81. package/dist/share/staging.d.ts.map +1 -1
  82. package/dist/share/staging.js +12 -4
  83. package/dist/share/staging.js.map +1 -1
  84. package/dist/voice/keyterm-builder.d.ts +4 -1
  85. package/dist/voice/keyterm-builder.d.ts.map +1 -1
  86. package/dist/voice/keyterm-builder.js +13 -6
  87. package/dist/voice/keyterm-builder.js.map +1 -1
  88. package/dist/ws/bridge.d.ts.map +1 -1
  89. package/dist/ws/bridge.js +6 -1
  90. package/dist/ws/bridge.js.map +1 -1
  91. package/dist/ws/connection.d.ts +15 -0
  92. package/dist/ws/connection.d.ts.map +1 -1
  93. package/dist/ws/connection.js +55 -8
  94. package/dist/ws/connection.js.map +1 -1
  95. package/dist/ws/dispatch.d.ts +22 -1
  96. package/dist/ws/dispatch.d.ts.map +1 -1
  97. package/dist/ws/dispatch.js +33 -15
  98. package/dist/ws/dispatch.js.map +1 -1
  99. package/dist/ws/host.d.ts +37 -0
  100. package/dist/ws/host.d.ts.map +1 -1
  101. package/dist/ws/host.js +37 -0
  102. package/dist/ws/host.js.map +1 -1
  103. package/dist/ws/rate-limit.d.ts +58 -0
  104. package/dist/ws/rate-limit.d.ts.map +1 -0
  105. package/dist/ws/rate-limit.js +62 -0
  106. package/dist/ws/rate-limit.js.map +1 -0
  107. package/dist/ws/run-session.d.ts +3 -0
  108. package/dist/ws/run-session.d.ts.map +1 -1
  109. package/dist/ws/run-session.js +23 -5
  110. package/dist/ws/run-session.js.map +1 -1
  111. package/dist/ws/turns.d.ts +13 -0
  112. package/dist/ws/turns.d.ts.map +1 -1
  113. package/dist/ws/turns.js +11 -1
  114. package/dist/ws/turns.js.map +1 -1
  115. package/package.json +5 -3
  116. package/src/agent/backend.ts +8 -6
  117. package/src/app.ts +46 -6
  118. package/src/config/env.ts +57 -0
  119. package/src/cron/scheduler.ts +14 -3
  120. package/src/db/client.ts +16 -5
  121. package/src/db/settings.ts +7 -2
  122. package/src/index.ts +37 -2
  123. package/src/middleware/auth.ts +30 -14
  124. package/src/middleware/passkeys.ts +29 -5
  125. package/src/observability/index.ts +150 -0
  126. package/src/observability/loggers.ts +174 -0
  127. package/src/observability/meter.ts +190 -0
  128. package/src/observability/types.ts +101 -0
  129. package/src/routes/brain.ts +10 -1
  130. package/src/routes/files.ts +9 -8
  131. package/src/routes/graph.ts +9 -8
  132. package/src/routes/health.ts +7 -0
  133. package/src/routes/models.ts +8 -5
  134. package/src/routes/render.ts +3 -2
  135. package/src/routes/share.ts +6 -3
  136. package/src/share/staging.ts +18 -4
  137. package/src/voice/keyterm-builder.ts +17 -8
  138. package/src/ws/bridge.ts +5 -1
  139. package/src/ws/connection.ts +63 -12
  140. package/src/ws/dispatch.ts +44 -15
  141. package/src/ws/host.ts +54 -0
  142. package/src/ws/rate-limit.ts +86 -0
  143. package/src/ws/run-session.ts +26 -7
  144. package/src/ws/turns.ts +19 -3
@@ -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
- * A client MAY echo the request's turnId (rev 2). When it does, it must match
11
- * the turn that raised the request — a stale echo from before a reconnect or
12
- * a follow-up would otherwise resolve the wrong turn's pending promise.
13
- * Absent turnId stays valid: the field is optional on the wire.
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(pending: { turnId: string }, echoed: string | undefined): boolean {
16
- return echoed === undefined || echoed === pending.turnId;
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
+ }
@@ -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
- console.warn(
45
- `[agent] session ${initial.sessionId} pinned profile "${target.droppedPin}" ` +
46
- `is unavailable; running on the default profile.`
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
- console.log("[agent] Turn timed out after", host.turnTimeoutMs, "ms");
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
- console.warn(`[ws] session ${sessionId} queue at ${formatMb(total)} across ${runningTurn.queue.length} messages`);
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
- console.error(
177
- `[ws] interactive id collision: "${id}" is already pending for another turn`
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;