@getmateo/client 0.0.0-stage → 0.18.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 (51) hide show
  1. package/LICENSE +211 -0
  2. package/README.md +43 -2
  3. package/dist/compat/normalize-provider-models.d.ts +11 -0
  4. package/dist/compat/normalize-provider-models.js +51 -0
  5. package/dist/connection/index.d.ts +51 -0
  6. package/dist/connection/index.js +113 -0
  7. package/dist/connection/legacy-workspaces.d.ts +19 -0
  8. package/dist/connection/legacy-workspaces.js +161 -0
  9. package/dist/connection/legacy.d.ts +31 -0
  10. package/dist/connection/legacy.js +245 -0
  11. package/dist/connection/owned.d.ts +36 -0
  12. package/dist/connection/owned.js +214 -0
  13. package/dist/creation/index.d.ts +40 -0
  14. package/dist/creation/index.js +197 -0
  15. package/dist/daemon-client-relay-e2ee-transport.d.ts +10 -0
  16. package/dist/daemon-client-relay-e2ee-transport.js +190 -0
  17. package/dist/daemon-client-runtime-metrics.d.ts +39 -0
  18. package/dist/daemon-client-runtime-metrics.js +173 -0
  19. package/dist/daemon-client-transport-types.d.ts +43 -0
  20. package/dist/daemon-client-transport-types.js +2 -0
  21. package/dist/daemon-client-transport-utils.d.ts +14 -0
  22. package/dist/daemon-client-transport-utils.js +127 -0
  23. package/dist/daemon-client-transport.d.ts +5 -0
  24. package/dist/daemon-client-transport.js +4 -0
  25. package/dist/daemon-client-websocket-transport.d.ts +15 -0
  26. package/dist/daemon-client-websocket-transport.js +183 -0
  27. package/dist/daemon-client.d.ts +1529 -0
  28. package/dist/daemon-client.js +5508 -0
  29. package/dist/fleet/index.d.ts +29 -0
  30. package/dist/fleet/index.js +81 -0
  31. package/dist/hosts/index.d.ts +16 -0
  32. package/dist/hosts/index.js +201 -0
  33. package/dist/index.d.ts +433 -0
  34. package/dist/index.js +584 -0
  35. package/dist/legacy-usage-icons.d.ts +2 -0
  36. package/dist/legacy-usage-icons.js +16 -0
  37. package/dist/node/buffering.d.ts +10 -0
  38. package/dist/node/buffering.js +28 -0
  39. package/dist/node/index.d.ts +17 -0
  40. package/dist/node/index.js +191 -0
  41. package/dist/node/ssh-tunnel.d.ts +9 -0
  42. package/dist/node/ssh-tunnel.js +81 -0
  43. package/dist/provider-snapshots/index.d.ts +21 -0
  44. package/dist/provider-snapshots/index.js +56 -0
  45. package/dist/terminal-stream-router.d.ts +25 -0
  46. package/dist/terminal-stream-router.js +62 -0
  47. package/dist/terminals/index.d.ts +80 -0
  48. package/dist/terminals/index.js +120 -0
  49. package/dist/timeline-subscription/index.d.ts +25 -0
  50. package/dist/timeline-subscription/index.js +56 -0
  51. package/package.json +64 -4
@@ -0,0 +1,197 @@
1
+ /** Client-owned observation and compatibility. UI callbacks never advance creation. */
2
+ export class CreationClient {
3
+ constructor(deps) {
4
+ this.deps = deps;
5
+ this.operations = new Map();
6
+ }
7
+ createAgent(input) {
8
+ const { onEvent, ...request } = input;
9
+ return this.start("agent", request, onEvent, () => this.legacyAgent(request));
10
+ }
11
+ createWorkspace(input) {
12
+ const { onEvent, ...request } = input;
13
+ return this.start("workspace", request, onEvent, async (operation) => {
14
+ if (request.workspaceId || request.agent?.agentId)
15
+ throw new Error("Update the host to use caller-selected creation IDs.");
16
+ const { agent, ...workspaceInput } = request;
17
+ const sourceCwd = request.source.kind === "directory" ? request.source.path : request.source.cwd;
18
+ const relativeCwd = agent && sourceCwd ? relativeDirectory(agent.config.cwd, sourceCwd) : undefined;
19
+ const workspace = await this.deps.legacyWorkspace(workspaceInput);
20
+ if (workspace.error || !workspace.workspace)
21
+ return workspace;
22
+ this.receive({
23
+ kind: "workspace",
24
+ idempotencyKey: operation.key,
25
+ revision: 1,
26
+ phase: "workspace_ready",
27
+ workspaceId: workspace.workspace.id,
28
+ agentId: null,
29
+ workspace: workspace.workspace,
30
+ setupSkippedReason: workspace.setupSkippedReason,
31
+ error: null,
32
+ });
33
+ if (!agent)
34
+ return workspace;
35
+ const cwd = `${workspace.workspace.workspaceDirectory.replace(/[\\/]+$/, "")}${relativeCwd ?? relativeDirectory(agent.config.cwd, workspace.workspace.projectRootPath)}`;
36
+ const created = await this.legacyAgent({
37
+ ...agent,
38
+ config: { ...agent.config, cwd },
39
+ workspaceId: workspace.workspace.id,
40
+ idempotencyKey: `${operation.key}:agent`,
41
+ });
42
+ return { ...workspace, agent: created.agent };
43
+ });
44
+ }
45
+ async legacyAgent(input) {
46
+ if (input.agentId)
47
+ throw new Error("Update the host to use caller-selected creation IDs.");
48
+ const { idempotencyKey: _key, ...unkeyed } = input;
49
+ const hasPrompt = Boolean(input.initialPrompt || input.images?.length || input.attachments?.length);
50
+ // COMPAT(creationLifecycle): added in v0.8.0, remove after 2027-03-11 once the daemon floor supports creationLifecycle.
51
+ // Preserve the original create-and-prompt RPC: old hosts use its prompt for
52
+ // titles, creation context and startup. Their keyed create cannot accept it.
53
+ const request = !hasPrompt && this.deps.supports("agentRequestReceipts") ? input : unkeyed;
54
+ return { agent: await this.deps.legacyAgent(request), error: null };
55
+ }
56
+ start(kind, input, observer, legacy) {
57
+ const key = typeof input.idempotencyKey === "string" ? input.idempotencyKey : this.deps.requestId();
58
+ const identity = JSON.stringify([kind, key]);
59
+ const { requestId: _requestId, ...intent } = input;
60
+ const fingerprint = JSON.stringify(intent, (_key, value) => value && typeof value === "object" && !Array.isArray(value)
61
+ ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)))
62
+ : value);
63
+ const previous = this.operations.get(identity);
64
+ if (previous) {
65
+ if (previous.fingerprint !== fingerprint)
66
+ return Promise.reject(new Error(`${kind}_request_key_conflict`));
67
+ if (observer) {
68
+ previous.observers.add(observer);
69
+ if (previous.snapshot)
70
+ this.notify(observer, previous.snapshot);
71
+ }
72
+ return previous.result;
73
+ }
74
+ let resolve;
75
+ let reject;
76
+ const result = new Promise((done, fail) => {
77
+ resolve = done;
78
+ reject = fail;
79
+ });
80
+ const operation = {
81
+ kind,
82
+ key,
83
+ input: { ...input, idempotencyKey: key },
84
+ fingerprint,
85
+ observers: new Set(observer ? [observer] : []),
86
+ result,
87
+ resolve,
88
+ reject,
89
+ settled: false,
90
+ modern: this.deps.supports("creationLifecycle"),
91
+ recovering: false,
92
+ };
93
+ this.operations.set(identity, operation);
94
+ if (operation.modern)
95
+ void this.submit(operation);
96
+ else
97
+ void legacy(operation).then((value) => this.finish(operation, value), (error) => this.fail(operation, error));
98
+ return result;
99
+ }
100
+ async submit(operation) {
101
+ try {
102
+ const result = await this.deps.request(operation.kind, {
103
+ ...operation.input,
104
+ subscribe: true,
105
+ });
106
+ if (result.creation)
107
+ this.receive(result.creation);
108
+ this.finish(operation, result);
109
+ }
110
+ catch (error) {
111
+ if (operation.settled ||
112
+ (error instanceof Error && "code" in error && error.code === "DAEMON_CONNECTION_LOST"))
113
+ return;
114
+ this.fail(operation, error);
115
+ }
116
+ }
117
+ receive(snapshot) {
118
+ const operation = this.operations.get(JSON.stringify([snapshot.kind, snapshot.idempotencyKey]));
119
+ if (!operation || (operation.snapshot && operation.snapshot.revision > snapshot.revision))
120
+ return;
121
+ if (operation.snapshot?.revision !== snapshot.revision) {
122
+ operation.snapshot = snapshot;
123
+ for (const observer of operation.observers)
124
+ this.notify(observer, snapshot);
125
+ }
126
+ if (operation.recovering && (snapshot.phase === "completed" || snapshot.phase === "failed")) {
127
+ this.finish(operation, {
128
+ agent: snapshot.agent,
129
+ workspace: snapshot.workspace,
130
+ creation: snapshot,
131
+ setupSkippedReason: snapshot.setupSkippedReason,
132
+ error: snapshot.error,
133
+ errorCode: snapshot.errorCode,
134
+ });
135
+ }
136
+ }
137
+ reconnect() {
138
+ for (const operation of this.operations.values()) {
139
+ if (operation.settled || !operation.modern || operation.recovering)
140
+ continue;
141
+ operation.recovering = true;
142
+ operation.stopObserving = this.deps.observe(operation.kind, operation.key, (snapshot) => {
143
+ if (!snapshot)
144
+ void this.submit(operation);
145
+ else {
146
+ // Re-subscription is authoritative even if its revision matches the last live event.
147
+ this.receive(snapshot);
148
+ }
149
+ }, (error) => this.fail(operation, error));
150
+ }
151
+ }
152
+ close() {
153
+ for (const operation of this.operations.values())
154
+ if (!operation.settled)
155
+ this.fail(operation, new Error("Daemon client closed"));
156
+ this.operations.clear();
157
+ }
158
+ finish(operation, result) {
159
+ if (operation.settled)
160
+ return;
161
+ operation.settled = true;
162
+ operation.stopObserving?.();
163
+ operation.resolve(result);
164
+ operation.observers.clear();
165
+ this.operations.delete(JSON.stringify([operation.kind, operation.key]));
166
+ }
167
+ fail(operation, error) {
168
+ if (operation.settled)
169
+ return;
170
+ operation.settled = true;
171
+ operation.stopObserving?.();
172
+ operation.reject(error instanceof Error ? error : new Error(String(error)));
173
+ operation.observers.clear();
174
+ this.operations.delete(JSON.stringify([operation.kind, operation.key]));
175
+ }
176
+ notify(observer, snapshot) {
177
+ try {
178
+ observer(snapshot);
179
+ }
180
+ catch {
181
+ /* Observation does not control execution. */
182
+ }
183
+ }
184
+ }
185
+ function relativeDirectory(cwd, source) {
186
+ const normalize = (value) => value.replace(/\\/g, "/").replace(/\/+$/, "");
187
+ const normalized = normalize(cwd), root = normalize(source);
188
+ // Parent traversal must never survive mapping into the newly created checkout.
189
+ if ([normalized, root].some((path) => path.split("/").includes("..")))
190
+ throw new Error("Agent directory must be inside the workspace source");
191
+ if (normalized === root)
192
+ return "";
193
+ if (!normalized.startsWith(`${root}/`))
194
+ throw new Error("Agent directory must be inside the workspace source");
195
+ return normalized.slice(root.length);
196
+ }
197
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,10 @@
1
+ import type { DaemonTransport, DaemonTransportFactory, TransportLogger } from "./daemon-client-transport-types.js";
2
+ export declare function createRelayE2eeTransportFactory(args: {
3
+ baseFactory: DaemonTransportFactory;
4
+ daemonPublicKeyB64: string;
5
+ logger: TransportLogger;
6
+ assertOutboundCapacity?: (wireBytes: number) => void;
7
+ }): DaemonTransportFactory;
8
+ export declare function createRelayTransportFactory(baseFactory: DaemonTransportFactory): DaemonTransportFactory;
9
+ export declare function createEncryptedTransport(base: DaemonTransport, daemonPublicKeyB64: string, logger: TransportLogger, assertOutboundCapacity?: (wireBytes: number) => void): DaemonTransport;
10
+ //# sourceMappingURL=daemon-client-relay-e2ee-transport.d.ts.map
@@ -0,0 +1,190 @@
1
+ import { maxBase64EncryptedPlaintextByteLength } from "@getmateo/relay";
2
+ import { MAX_RELAY_WEBSOCKET_MESSAGE_BYTES } from "@getmateo/protocol/websocket-message-limit";
3
+ import { createClientChannel, } from "@getmateo/relay/e2ee";
4
+ import { extractRelayMessage, normalizeTransportPayload, messageTooLargeError, } from "./daemon-client-transport-utils.js";
5
+ export function createRelayE2eeTransportFactory(args) {
6
+ return ({ url }) => {
7
+ const base = args.baseFactory({ url });
8
+ return createEncryptedTransport(base, args.daemonPublicKeyB64, args.logger, args.assertOutboundCapacity);
9
+ };
10
+ }
11
+ export function createRelayTransportFactory(baseFactory) {
12
+ // The relay upgrade precedes E2EE. Only the encrypted hello may carry daemon credentials.
13
+ return ({ url }) => baseFactory({ url });
14
+ }
15
+ export function createEncryptedTransport(base, daemonPublicKeyB64, logger, assertOutboundCapacity = () => { }) {
16
+ let channel = null;
17
+ let opened = false;
18
+ let closed = false;
19
+ const openHandlers = new Set();
20
+ const closeHandlers = new Set();
21
+ const errorHandlers = new Set();
22
+ const messageHandlers = new Set();
23
+ const emitOpen = () => {
24
+ if (opened || closed) {
25
+ return;
26
+ }
27
+ opened = true;
28
+ emitHandlers(openHandlers);
29
+ };
30
+ const emitClose = (event) => {
31
+ if (closed) {
32
+ return;
33
+ }
34
+ closed = true;
35
+ emitHandlers(closeHandlers, event);
36
+ };
37
+ const emitError = (event) => {
38
+ if (closed) {
39
+ return;
40
+ }
41
+ emitHandlers(errorHandlers, event);
42
+ };
43
+ const emitMessage = (data) => {
44
+ if (closed) {
45
+ return;
46
+ }
47
+ emitHandlers(messageHandlers, data, data instanceof ArrayBuffer);
48
+ };
49
+ const relayTransport = {
50
+ send: (data) => {
51
+ if (typeof data === "string") {
52
+ return base.send(data);
53
+ }
54
+ if (ArrayBuffer.isView(data)) {
55
+ return base.send(normalizeTransportPayload(data));
56
+ }
57
+ if (data instanceof ArrayBuffer) {
58
+ return base.send(data);
59
+ }
60
+ return base.send(String(data));
61
+ },
62
+ close: (code, reason) => base.close(code, reason),
63
+ onmessage: null,
64
+ onclose: null,
65
+ onerror: null,
66
+ };
67
+ const startHandshake = async () => {
68
+ try {
69
+ channel = await createClientChannel(relayTransport, daemonPublicKeyB64, {
70
+ onopen: emitOpen,
71
+ onmessage: (data) => emitMessage(data),
72
+ onclose: (code, reason) => emitClose({ code, reason }),
73
+ onerror: (error) => emitError(error),
74
+ });
75
+ }
76
+ catch (error) {
77
+ logger.warn({ err: normalizeTransportError(error) }, "relay_e2ee_handshake_failed");
78
+ emitError(error);
79
+ // Browser WebSocket.close only accepts 1000 or 3000-4999.
80
+ // Use an app-defined code so this path works in browser and Node runtimes.
81
+ base.close(4001, "E2EE handshake failed");
82
+ }
83
+ };
84
+ base.onOpen(() => {
85
+ void startHandshake();
86
+ });
87
+ // The channel decrypts after an await, so a close or error that arrives in the same task as a
88
+ // frame would otherwise be delivered first and drop the frame. A daemon rejects a hello by
89
+ // sending hello.rejected and closing immediately, which made the password prompt flaky.
90
+ let inbound = Promise.resolve();
91
+ const enqueueInbound = (task) => {
92
+ inbound = inbound.then(task).catch(() => undefined);
93
+ };
94
+ base.onMessage((data, isBinary) => {
95
+ const message = extractRelayMessage(data, isBinary);
96
+ enqueueInbound(() => relayTransport.onmessage?.(message));
97
+ });
98
+ base.onClose((event) => {
99
+ enqueueInbound(() => {
100
+ const record = event;
101
+ relayTransport.onclose?.(record?.code ?? 0, record?.reason ?? "");
102
+ emitClose(event);
103
+ });
104
+ });
105
+ base.onError((event) => {
106
+ enqueueInbound(() => {
107
+ relayTransport.onerror?.(event instanceof Error ? event : new Error(String(event)));
108
+ emitError(event);
109
+ });
110
+ });
111
+ return {
112
+ supportsDrain: base.supportsDrain,
113
+ // Use the base64 budget even when binary ciphertext was negotiated, so mixed-version
114
+ // encrypted channels obey the same relay limit without another framing contract.
115
+ maxFrameBytes: maxBase64EncryptedPlaintextByteLength(MAX_RELAY_WEBSOCKET_MESSAGE_BYTES),
116
+ send: (data) => {
117
+ if (!channel) {
118
+ throw new Error("Encrypted channel not ready");
119
+ }
120
+ const payload = normalizeTransportPayload(data);
121
+ // Reject synchronously so the requesting operation fails without closing the transport.
122
+ const wireBytes = channel.outboundWireByteLength(payload);
123
+ if (wireBytes > MAX_RELAY_WEBSOCKET_MESSAGE_BYTES) {
124
+ throw messageTooLargeError(wireBytes, MAX_RELAY_WEBSOCKET_MESSAGE_BYTES);
125
+ }
126
+ // Encryption hands off synchronously up to send's first await. Reject capacity
127
+ // failures here so a routed sender loses only its own channel.
128
+ assertOutboundCapacity(wireBytes);
129
+ return channel.send(payload).catch((error) => {
130
+ emitError(error);
131
+ throw error;
132
+ });
133
+ },
134
+ close: (code, reason) => {
135
+ if (channel) {
136
+ channel.close(code, reason);
137
+ }
138
+ else {
139
+ base.close(code, reason);
140
+ }
141
+ emitClose({ code, reason });
142
+ },
143
+ onMessage: (handler) => {
144
+ messageHandlers.add(handler);
145
+ return () => messageHandlers.delete(handler);
146
+ },
147
+ onOpen: (handler) => {
148
+ openHandlers.add(handler);
149
+ if (opened) {
150
+ invokeHandler(handler);
151
+ }
152
+ return () => openHandlers.delete(handler);
153
+ },
154
+ onClose: (handler) => {
155
+ closeHandlers.add(handler);
156
+ if (closed) {
157
+ invokeHandler(handler);
158
+ }
159
+ return () => closeHandlers.delete(handler);
160
+ },
161
+ onError: (handler) => {
162
+ errorHandlers.add(handler);
163
+ return () => errorHandlers.delete(handler);
164
+ },
165
+ };
166
+ }
167
+ function emitHandlers(handlers, ...args) {
168
+ for (const handler of handlers) {
169
+ invokeHandler(handler, ...args);
170
+ }
171
+ }
172
+ function invokeHandler(handler, ...args) {
173
+ try {
174
+ handler(...args);
175
+ }
176
+ catch {
177
+ // no-op
178
+ }
179
+ }
180
+ function normalizeTransportError(error) {
181
+ if (error instanceof Error) {
182
+ return {
183
+ name: error.name,
184
+ message: error.message,
185
+ ...(typeof error.stack === "string" ? { stack: error.stack } : {}),
186
+ };
187
+ }
188
+ return { message: String(error) };
189
+ }
190
+ //# sourceMappingURL=daemon-client-relay-e2ee-transport.js.map
@@ -0,0 +1,39 @@
1
+ import type { SessionOutboundMessage } from "@getmateo/protocol/messages";
2
+ interface RuntimeMetricsLogger {
3
+ info(obj: object, msg?: string): void;
4
+ }
5
+ interface RuntimeMetricsContext {
6
+ connectionPath: "direct" | "relay";
7
+ serverId: string | null;
8
+ getConnectionStatus: () => string;
9
+ }
10
+ interface RuntimeMetricsOptions {
11
+ windowMs?: number;
12
+ }
13
+ export declare class DaemonClientRuntimeMetrics {
14
+ private readonly logger;
15
+ private readonly context;
16
+ private readonly startedAt;
17
+ private readonly windowMs;
18
+ private readonly buckets;
19
+ private readonly inboundMessageCounts;
20
+ private readonly inboundMessageBytes;
21
+ private readonly inboundMessageHandlerMs;
22
+ private readonly inboundAgentStreamCounts;
23
+ private readonly inboundAgentStreamByAgentCounts;
24
+ private readonly inboundBinaryFrameCounts;
25
+ constructor(logger: RuntimeMetricsLogger, context: RuntimeMetricsContext, options?: RuntimeMetricsOptions);
26
+ recordMessage(type: string, bytes: number, handlerMs: number): void;
27
+ recordAgentStream(payload: Extract<SessionOutboundMessage, {
28
+ type: "agent_stream";
29
+ }>["payload"]): void;
30
+ recordBinaryFrame(kind: string, bytes: number, handlerMs: number): void;
31
+ flush(options?: {
32
+ final?: boolean;
33
+ }): void;
34
+ private consumeCurrentBucket;
35
+ private pruneBuckets;
36
+ private aggregateBuckets;
37
+ }
38
+ export {};
39
+ //# sourceMappingURL=daemon-client-runtime-metrics.d.ts.map
@@ -0,0 +1,173 @@
1
+ const DEFAULT_ROLLING_WINDOW_MS = 60000;
2
+ export class DaemonClientRuntimeMetrics {
3
+ constructor(logger, context, options) {
4
+ this.logger = logger;
5
+ this.context = context;
6
+ this.startedAt = Date.now();
7
+ this.buckets = [];
8
+ this.inboundMessageCounts = new Map();
9
+ this.inboundMessageBytes = new Map();
10
+ this.inboundMessageHandlerMs = new Map();
11
+ this.inboundAgentStreamCounts = new Map();
12
+ this.inboundAgentStreamByAgentCounts = new Map();
13
+ this.inboundBinaryFrameCounts = new Map();
14
+ this.windowMs =
15
+ typeof options?.windowMs === "number" && options.windowMs > 0
16
+ ? options.windowMs
17
+ : DEFAULT_ROLLING_WINDOW_MS;
18
+ }
19
+ recordMessage(type, bytes, handlerMs) {
20
+ incrementCount(this.inboundMessageCounts, type, 1);
21
+ incrementCount(this.inboundMessageBytes, type, bytes);
22
+ incrementHandlerTiming(this.inboundMessageHandlerMs, type, handlerMs);
23
+ }
24
+ recordAgentStream(payload) {
25
+ const { agentId, event } = payload;
26
+ const eventType = event.type === "timeline" ? `timeline:${event.item.type}` : event.type;
27
+ incrementCount(this.inboundAgentStreamCounts, eventType, 1);
28
+ incrementCount(this.inboundAgentStreamByAgentCounts, agentId, 1);
29
+ }
30
+ recordBinaryFrame(kind, bytes, handlerMs) {
31
+ incrementCount(this.inboundBinaryFrameCounts, kind, 1);
32
+ incrementCount(this.inboundMessageBytes, `binary:${kind}`, bytes);
33
+ incrementHandlerTiming(this.inboundMessageHandlerMs, `binary:${kind}`, handlerMs);
34
+ }
35
+ flush(options) {
36
+ const now = Date.now();
37
+ const bucket = this.consumeCurrentBucket(now);
38
+ if (bucket) {
39
+ this.buckets.push(bucket);
40
+ }
41
+ this.pruneBuckets(now);
42
+ const aggregate = this.aggregateBuckets();
43
+ const hasActivity = aggregate.inboundMessageCounts.size > 0 || aggregate.inboundBinaryFrameCounts.size > 0;
44
+ if (!hasActivity && !options?.final) {
45
+ return;
46
+ }
47
+ this.logger.info({
48
+ windowMs: Math.min(this.windowMs, Math.max(0, now - this.startedAt)),
49
+ rollingWindowMs: this.windowMs,
50
+ bucketCount: this.buckets.length,
51
+ final: Boolean(options?.final),
52
+ connectionPath: this.context.connectionPath,
53
+ serverId: this.context.serverId,
54
+ connectionStatus: this.context.getConnectionStatus(),
55
+ inboundMessageTypesTop: getTopCounts(aggregate.inboundMessageCounts, 20),
56
+ inboundMessageBytesTop: getTopCounts(aggregate.inboundMessageBytes, 20),
57
+ inboundAgentStreamTypesTop: getTopCounts(aggregate.inboundAgentStreamCounts, 20),
58
+ inboundAgentStreamAgentsTop: getTopCounts(aggregate.inboundAgentStreamByAgentCounts, 20),
59
+ inboundBinaryFrameTypesTop: getTopCounts(aggregate.inboundBinaryFrameCounts, 12),
60
+ handlerTimingTop: getTopHandlerTimings(aggregate.inboundMessageHandlerMs, 20),
61
+ }, "ws_runtime_metrics_client");
62
+ }
63
+ consumeCurrentBucket(now) {
64
+ const hasActivity = this.inboundMessageCounts.size > 0 || this.inboundBinaryFrameCounts.size > 0;
65
+ if (!hasActivity) {
66
+ return null;
67
+ }
68
+ const bucket = {
69
+ inboundMessageCounts: new Map(this.inboundMessageCounts),
70
+ inboundMessageBytes: new Map(this.inboundMessageBytes),
71
+ inboundMessageHandlerMs: cloneHandlerTimingMap(this.inboundMessageHandlerMs),
72
+ inboundAgentStreamCounts: new Map(this.inboundAgentStreamCounts),
73
+ inboundAgentStreamByAgentCounts: new Map(this.inboundAgentStreamByAgentCounts),
74
+ inboundBinaryFrameCounts: new Map(this.inboundBinaryFrameCounts),
75
+ endedAt: now,
76
+ };
77
+ this.inboundMessageCounts.clear();
78
+ this.inboundMessageBytes.clear();
79
+ this.inboundMessageHandlerMs.clear();
80
+ this.inboundAgentStreamCounts.clear();
81
+ this.inboundAgentStreamByAgentCounts.clear();
82
+ this.inboundBinaryFrameCounts.clear();
83
+ return bucket;
84
+ }
85
+ pruneBuckets(now) {
86
+ const cutoff = now - this.windowMs;
87
+ while (this.buckets.length > 0 && this.buckets[0].endedAt < cutoff) {
88
+ this.buckets.shift();
89
+ }
90
+ }
91
+ aggregateBuckets() {
92
+ const aggregate = createEmptyBucket(Date.now());
93
+ for (const bucket of this.buckets) {
94
+ mergeCountMap(aggregate.inboundMessageCounts, bucket.inboundMessageCounts);
95
+ mergeCountMap(aggregate.inboundMessageBytes, bucket.inboundMessageBytes);
96
+ mergeHandlerTimingMap(aggregate.inboundMessageHandlerMs, bucket.inboundMessageHandlerMs);
97
+ mergeCountMap(aggregate.inboundAgentStreamCounts, bucket.inboundAgentStreamCounts);
98
+ mergeCountMap(aggregate.inboundAgentStreamByAgentCounts, bucket.inboundAgentStreamByAgentCounts);
99
+ mergeCountMap(aggregate.inboundBinaryFrameCounts, bucket.inboundBinaryFrameCounts);
100
+ }
101
+ return aggregate;
102
+ }
103
+ }
104
+ function createEmptyBucket(endedAt) {
105
+ return {
106
+ inboundMessageCounts: new Map(),
107
+ inboundMessageBytes: new Map(),
108
+ inboundMessageHandlerMs: new Map(),
109
+ inboundAgentStreamCounts: new Map(),
110
+ inboundAgentStreamByAgentCounts: new Map(),
111
+ inboundBinaryFrameCounts: new Map(),
112
+ endedAt,
113
+ };
114
+ }
115
+ function incrementCount(map, key, amount) {
116
+ map.set(key, (map.get(key) ?? 0) + amount);
117
+ }
118
+ function incrementHandlerTiming(map, key, handlerMs) {
119
+ const existing = map.get(key);
120
+ if (existing) {
121
+ existing.count += 1;
122
+ existing.totalMs += handlerMs;
123
+ existing.maxMs = Math.max(existing.maxMs, handlerMs);
124
+ return;
125
+ }
126
+ map.set(key, {
127
+ count: 1,
128
+ totalMs: handlerMs,
129
+ maxMs: handlerMs,
130
+ });
131
+ }
132
+ function cloneHandlerTimingMap(map) {
133
+ return new Map([...map.entries()].map(([key, value]) => [
134
+ key,
135
+ { count: value.count, totalMs: value.totalMs, maxMs: value.maxMs },
136
+ ]));
137
+ }
138
+ function mergeCountMap(target, source) {
139
+ for (const [key, value] of source) {
140
+ incrementCount(target, key, value);
141
+ }
142
+ }
143
+ function mergeHandlerTimingMap(target, source) {
144
+ for (const [key, value] of source) {
145
+ const existing = target.get(key);
146
+ if (existing) {
147
+ existing.count += value.count;
148
+ existing.totalMs += value.totalMs;
149
+ existing.maxMs = Math.max(existing.maxMs, value.maxMs);
150
+ continue;
151
+ }
152
+ target.set(key, {
153
+ count: value.count,
154
+ totalMs: value.totalMs,
155
+ maxMs: value.maxMs,
156
+ });
157
+ }
158
+ }
159
+ function getTopCounts(map, limit) {
160
+ return [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, limit);
161
+ }
162
+ function getTopHandlerTimings(map, limit) {
163
+ const rows = [...map.entries()].map(([type, value]) => ({
164
+ type,
165
+ count: value.count,
166
+ totalMs: Math.round(value.totalMs),
167
+ avgMs: Math.round((value.totalMs / value.count) * 100) / 100,
168
+ maxMs: Math.round(value.maxMs * 100) / 100,
169
+ }));
170
+ rows.sort((a, b) => b.totalMs - a.totalMs);
171
+ return rows.slice(0, limit);
172
+ }
173
+ //# sourceMappingURL=daemon-client-runtime-metrics.js.map
@@ -0,0 +1,43 @@
1
+ export interface DaemonTransport {
2
+ /** False when the underlying socket cannot report write drain. */
3
+ supportsDrain?: boolean;
4
+ maxFrameBytes?: number;
5
+ send: (data: string | Uint8Array | ArrayBuffer) => void | Promise<void>;
6
+ close: (code?: number, reason?: string) => void;
7
+ onMessage: (handler: (data: unknown, isBinary: boolean) => void | Promise<void>) => () => void;
8
+ onOpen: (handler: () => void) => () => void;
9
+ onClose: (handler: (event?: unknown) => void) => () => void;
10
+ onError: (handler: (event?: unknown) => void) => () => void;
11
+ }
12
+ export type DaemonTransportFactory = (options: {
13
+ url: string;
14
+ headers?: Record<string, string>;
15
+ protocols?: string[];
16
+ }) => DaemonTransport;
17
+ export interface WebSocketFactory {
18
+ (url: string, options?: {
19
+ headers?: Record<string, string>;
20
+ protocols?: string[];
21
+ }): WebSocketLike;
22
+ supportsDrain?: boolean;
23
+ }
24
+ export interface WebSocketLike {
25
+ bufferedAmount?: number;
26
+ readyState: number;
27
+ send: (data: string | Uint8Array | ArrayBuffer) => void;
28
+ close: (code?: number, reason?: string) => void;
29
+ binaryType?: string;
30
+ on?: (event: string, listener: (...args: unknown[]) => void) => void;
31
+ off?: (event: string, listener: (...args: unknown[]) => void) => void;
32
+ removeListener?: (event: string, listener: (...args: unknown[]) => void) => void;
33
+ addEventListener?: (event: string, listener: (event: unknown) => void) => void;
34
+ removeEventListener?: (event: string, listener: (event: unknown) => void) => void;
35
+ onopen?: ((event: unknown) => void) | null;
36
+ onclose?: ((event: unknown) => void) | null;
37
+ onerror?: ((event: unknown) => void) | null;
38
+ onmessage?: ((event: unknown) => void) | null;
39
+ }
40
+ export interface TransportLogger {
41
+ warn(obj: object, msg?: string): void;
42
+ }
43
+ //# sourceMappingURL=daemon-client-transport-types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=daemon-client-transport-types.js.map
@@ -0,0 +1,14 @@
1
+ export declare function copyArrayBufferViewToBuffer(data: ArrayBufferView): ArrayBuffer;
2
+ export declare function normalizeTransportPayload(data: string | Uint8Array | ArrayBuffer): string | ArrayBuffer;
3
+ export interface RelayTransportMessage {
4
+ data: string | ArrayBuffer;
5
+ isBinary: boolean;
6
+ }
7
+ export declare function extractRelayMessage(event: unknown, nodeIsBinary?: boolean): RelayTransportMessage;
8
+ export declare function describeTransportClose(event?: unknown): string;
9
+ export declare function describeTransportError(event?: unknown): string;
10
+ export declare function safeRandomId(): string;
11
+ export declare function decodeMessageData(data: unknown): string | null;
12
+ export declare function encodeUtf8String(value: string): Uint8Array;
13
+ export declare function messageTooLargeError(size: number, limit: number): Error;
14
+ //# sourceMappingURL=daemon-client-transport-utils.d.ts.map