@code-yeongyu/senpi 2026.8.31 → 2026.9.2-4
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/CHANGELOG.md +119 -2
- package/dist/beta/omo-local-update-fingerprint.d.ts.map +1 -1
- package/dist/beta/omo-local-update-fingerprint.js +0 -1
- package/dist/beta/omo-local-update-fingerprint.js.map +1 -1
- package/dist/core/agent-session.d.ts +1 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +7 -4
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/options.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/options.js +6 -2
- package/dist/core/extensions/builtin/claude-sdk-oauth/options.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/stream.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/stream.js +2 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/stream.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/context-pipeline.d.ts +6 -0
- package/dist/core/extensions/builtin/compaction/context-pipeline.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/context-pipeline.js +11 -0
- package/dist/core/extensions/builtin/compaction/context-pipeline.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/extension-wiring.js +1 -1
- package/dist/core/extensions/builtin/compaction/extension-wiring.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/index.js +4 -4
- package/dist/core/extensions/builtin/compaction/index.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-1.d.ts +3 -0
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-1.d.ts.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-1.js +110 -0
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-1.js.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5.js +2 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-4-5.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-4-5.js +7 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-4-5.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-4-6.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-4-6.js +7 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-4-6.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-4-7.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-4-7.js +7 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-4-7.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-4-8.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-4-8.js +7 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-4-8.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-5.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-5.js +2 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-5.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/execution-tooling.d.ts +50 -0
- package/dist/core/extensions/builtin/prompt-preset/execution-tooling.d.ts.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset/execution-tooling.js +66 -0
- package/dist/core/extensions/builtin/prompt-preset/execution-tooling.js.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.d.ts +5 -1
- package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.js +6 -1
- package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-6.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-6.js +11 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-6.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-7.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-7.js +11 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-7.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k3.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k3.js +2 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k3.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/presets.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/presets.js +18 -1
- package/dist/core/extensions/builtin/prompt-preset/presets.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/settings.d.ts +1 -1
- package/dist/core/extensions/builtin/prompt-preset/settings.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/settings.js +1 -0
- package/dist/core/extensions/builtin/prompt-preset/settings.js.map +1 -1
- package/dist/core/extensions/builtin/recommended-models/index.d.ts +1 -1
- package/dist/core/extensions/builtin/recommended-models/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/recommended-models/index.js +1 -1
- package/dist/core/extensions/builtin/recommended-models/index.js.map +1 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +17 -8
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/retry-fallback/settings.d.ts.map +1 -1
- package/dist/core/retry-fallback/settings.js +1 -0
- package/dist/core/retry-fallback/settings.js.map +1 -1
- package/dist/core/settings-manager.d.ts +2 -2
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +5 -3
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +4 -4
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +10 -6
- package/dist/main.js.map +1 -1
- package/dist/modes/app-server/daemon/process.d.ts +13 -2
- package/dist/modes/app-server/daemon/process.d.ts.map +1 -1
- package/dist/modes/app-server/daemon/process.js +58 -12
- package/dist/modes/app-server/daemon/process.js.map +1 -1
- package/dist/modes/app-server/daemon.js +62 -4
- package/dist/modes/app-server/daemon.js.map +1 -1
- package/dist/modes/index.d.ts +1 -1
- package/dist/modes/index.d.ts.map +1 -1
- package/dist/modes/index.js +1 -1
- package/dist/modes/index.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +11 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +35 -6
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/tips/catalog/ethos-tips.js +1 -1
- package/dist/modes/interactive/tips/catalog/ethos-tips.js.map +1 -1
- package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
- package/dist/modes/rpc/connection-handler.js +8 -3
- package/dist/modes/rpc/connection-handler.js.map +1 -1
- package/dist/modes/rpc/custom-capability.d.ts +1 -0
- package/dist/modes/rpc/custom-capability.d.ts.map +1 -1
- package/dist/modes/rpc/custom-capability.js +1 -0
- package/dist/modes/rpc/custom-capability.js.map +1 -1
- package/dist/modes/rpc/host-ensure.d.ts.map +1 -1
- package/dist/modes/rpc/host-ensure.js +114 -22
- package/dist/modes/rpc/host-ensure.js.map +1 -1
- package/dist/modes/rpc/host-lifecycle.d.ts +15 -0
- package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
- package/dist/modes/rpc/host-lifecycle.js +180 -55
- package/dist/modes/rpc/host-lifecycle.js.map +1 -1
- package/dist/modes/rpc/host-watchdog.d.ts +2 -2
- package/dist/modes/rpc/host-watchdog.d.ts.map +1 -1
- package/dist/modes/rpc/host-watchdog.js +89 -21
- package/dist/modes/rpc/host-watchdog.js.map +1 -1
- package/dist/modes/rpc/multi-session-host.d.ts +4 -4
- package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
- package/dist/modes/rpc/multi-session-host.js +98 -60
- package/dist/modes/rpc/multi-session-host.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +8 -0
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +70 -8
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
- package/dist/modes/rpc/session-command-router.js +7 -2
- package/dist/modes/rpc/session-command-router.js.map +1 -1
- package/dist/modes/rpc/session-event-fanout.d.ts +38 -0
- package/dist/modes/rpc/session-event-fanout.d.ts.map +1 -0
- package/dist/modes/rpc/session-event-fanout.js +133 -0
- package/dist/modes/rpc/session-event-fanout.js.map +1 -0
- package/dist/modes/rpc/session-event-writer.d.ts +4 -13
- package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
- package/dist/modes/rpc/session-event-writer.js +34 -96
- package/dist/modes/rpc/session-event-writer.js.map +1 -1
- package/dist/modes/rpc/socket-transport.d.ts +13 -0
- package/dist/modes/rpc/socket-transport.d.ts.map +1 -0
- package/dist/modes/rpc/socket-transport.js +92 -0
- package/dist/modes/rpc/socket-transport.js.map +1 -0
- package/docs/extensions.md +1 -1
- package/docs/rpc.md +11 -5
- package/docs/settings.md +8 -8
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +57 -0
- package/node_modules/@code-yeongyu/senpi-codemode/README.md +4 -2
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@code-yeongyu/senpi-codemode/src/extension/skill-contribution.ts +43 -9
- package/node_modules/@code-yeongyu/senpi-codemode/src/index.ts +4 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt.ts +10 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/SKILL.md +1 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/runtime-apis.md +1 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool-options.ts +3 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool.ts +2 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts +3 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +2 -2
- package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic.d.ts +5 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic.js +26 -4
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/anthropic.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/google.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/groq.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry-profile/profiles.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry-profile/profiles.js +3 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry-profile/profiles.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/node_modules/@earendil-works/pi-pty/package.json +1 -1
- package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/package.json +7 -7
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { SocketEventSinkActor } from "./socket-event-fanout.js";
|
|
2
|
+
export const RENDERED_COMPONENT_RECORD = "__senpiRenderedComponent";
|
|
3
|
+
export class SessionEventFanout {
|
|
4
|
+
constructor() {
|
|
5
|
+
this.connections = new Map();
|
|
6
|
+
this.sessionSnapshots = new Map();
|
|
7
|
+
this.connectionCapabilities = new Map();
|
|
8
|
+
this.connectionSessions = new Map();
|
|
9
|
+
this.registeredCapabilityConnections = new Set();
|
|
10
|
+
}
|
|
11
|
+
registerConnection(id, connection) {
|
|
12
|
+
const actor = new SocketEventSinkActor(connection, () => {
|
|
13
|
+
if (this.connections.get(id)?.actor === actor) {
|
|
14
|
+
this.connections.delete(id);
|
|
15
|
+
this.connectionCapabilities.delete(id);
|
|
16
|
+
this.connectionSessions.delete(id);
|
|
17
|
+
this.registeredCapabilityConnections.delete(id);
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
this.connections.set(id, { connection, actor });
|
|
21
|
+
this.connectionCapabilities.set(id, new Set());
|
|
22
|
+
this.connectionSessions.set(id, new Set());
|
|
23
|
+
}
|
|
24
|
+
unregisterConnection(id) {
|
|
25
|
+
const registered = this.connections.get(id);
|
|
26
|
+
if (!registered)
|
|
27
|
+
return;
|
|
28
|
+
registered.actor.close();
|
|
29
|
+
this.connections.delete(id);
|
|
30
|
+
this.connectionCapabilities.delete(id);
|
|
31
|
+
this.connectionSessions.delete(id);
|
|
32
|
+
this.registeredCapabilityConnections.delete(id);
|
|
33
|
+
}
|
|
34
|
+
attachConnectionToSession(id, sessionId) {
|
|
35
|
+
if (!this.connections.has(id))
|
|
36
|
+
return;
|
|
37
|
+
const sessions = this.connectionSessions.get(id) ?? new Set();
|
|
38
|
+
if (sessions.has(sessionId))
|
|
39
|
+
return;
|
|
40
|
+
sessions.add(sessionId);
|
|
41
|
+
this.connectionSessions.set(id, sessions);
|
|
42
|
+
this.replaySnapshot(id, sessionId);
|
|
43
|
+
}
|
|
44
|
+
detachConnectionFromSession(id, sessionId) {
|
|
45
|
+
this.connectionSessions.get(id)?.delete(sessionId);
|
|
46
|
+
}
|
|
47
|
+
setConnectionCapabilities(id, capabilities) {
|
|
48
|
+
const registered = this.connections.get(id);
|
|
49
|
+
if (!registered)
|
|
50
|
+
return;
|
|
51
|
+
const wasCapable = this.connectionCapabilities.get(id)?.has("rendered_components") ?? false;
|
|
52
|
+
this.connectionCapabilities.set(id, new Set(capabilities));
|
|
53
|
+
this.registeredCapabilityConnections.add(id);
|
|
54
|
+
if (!wasCapable && capabilities.includes("rendered_components"))
|
|
55
|
+
for (const sessionId of this.connectionSessions.get(id) ?? [])
|
|
56
|
+
this.replayRendered(id, sessionId);
|
|
57
|
+
}
|
|
58
|
+
clearConnectionCapabilities(id) {
|
|
59
|
+
if (this.connections.has(id)) {
|
|
60
|
+
this.connectionCapabilities.set(id, new Set());
|
|
61
|
+
this.registeredCapabilityConnections.delete(id);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
hasRegisteredConnectionCapabilities(id) {
|
|
65
|
+
return this.registeredCapabilityConnections.has(id);
|
|
66
|
+
}
|
|
67
|
+
getConnectionCapabilities(id) {
|
|
68
|
+
if (!this.registeredCapabilityConnections.has(id))
|
|
69
|
+
return undefined;
|
|
70
|
+
return [...(this.connectionCapabilities.get(id) ?? [])];
|
|
71
|
+
}
|
|
72
|
+
hasCapableConnection(sessionId) {
|
|
73
|
+
for (const [id, capabilities] of this.connectionCapabilities)
|
|
74
|
+
if (capabilities.has("rendered_components") && this.connectionSessions.get(id)?.has(sessionId))
|
|
75
|
+
return true;
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
targets(sessionId, targetId, isTargeted, rendered) {
|
|
79
|
+
if (isTargeted)
|
|
80
|
+
return [targetId];
|
|
81
|
+
if (rendered)
|
|
82
|
+
return this.connections.size > 0
|
|
83
|
+
? [...this.connections.keys()].filter((id) => this.connectionCapabilities.get(id)?.has("rendered_components") &&
|
|
84
|
+
this.connectionSessions.get(id)?.has(sessionId))
|
|
85
|
+
: [undefined];
|
|
86
|
+
return this.connections.size > 0
|
|
87
|
+
? [...this.connections.keys()].filter((id) => this.connectionSessions.get(id)?.has(sessionId))
|
|
88
|
+
: [undefined];
|
|
89
|
+
}
|
|
90
|
+
get(id) {
|
|
91
|
+
return this.connections.get(id);
|
|
92
|
+
}
|
|
93
|
+
values() {
|
|
94
|
+
return this.connections.values();
|
|
95
|
+
}
|
|
96
|
+
broadcast(line) {
|
|
97
|
+
for (const { actor } of this.connections.values())
|
|
98
|
+
actor.enqueue(line);
|
|
99
|
+
}
|
|
100
|
+
rememberSnapshot(sessionId, value, line) {
|
|
101
|
+
const event = value.assistantMessageEvent;
|
|
102
|
+
const record = { line, rendered: value[RENDERED_COMPONENT_RECORD] === true };
|
|
103
|
+
if (value.type === "message_start" || (value.type === "message_update" && event?.type === "text_start")) {
|
|
104
|
+
this.sessionSnapshots.set(sessionId, [record]);
|
|
105
|
+
}
|
|
106
|
+
else if (this.sessionSnapshots.has(sessionId)) {
|
|
107
|
+
this.sessionSnapshots.get(sessionId)?.push(record);
|
|
108
|
+
}
|
|
109
|
+
if (value.type === "message_end")
|
|
110
|
+
this.sessionSnapshots.delete(sessionId);
|
|
111
|
+
}
|
|
112
|
+
forgetSession(sessionId) {
|
|
113
|
+
this.sessionSnapshots.delete(sessionId);
|
|
114
|
+
}
|
|
115
|
+
replaySnapshot(id, sessionId) {
|
|
116
|
+
const actor = this.connections.get(id)?.actor;
|
|
117
|
+
if (!actor)
|
|
118
|
+
return;
|
|
119
|
+
const capable = this.connectionCapabilities.get(id)?.has("rendered_components") ?? false;
|
|
120
|
+
for (const record of this.sessionSnapshots.get(sessionId) ?? [])
|
|
121
|
+
if (!record.rendered || capable)
|
|
122
|
+
actor.enqueue(record.line);
|
|
123
|
+
}
|
|
124
|
+
replayRendered(id, sessionId) {
|
|
125
|
+
const actor = this.connections.get(id)?.actor;
|
|
126
|
+
if (!actor)
|
|
127
|
+
return;
|
|
128
|
+
for (const record of this.sessionSnapshots.get(sessionId) ?? [])
|
|
129
|
+
if (record.rendered)
|
|
130
|
+
actor.enqueue(record.line);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
//# sourceMappingURL=session-event-fanout.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-event-fanout.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-event-fanout.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAUhE,MAAM,CAAC,MAAM,yBAAyB,GAAG,0BAA0B,CAAC;AASpE,MAAM,OAAO,kBAAkB;IAA/B;QACkB,gBAAW,GAAG,IAAI,GAAG,EAAgC,CAAC;QACtD,qBAAgB,GAAG,IAAI,GAAG,EAA4B,CAAC;QACvD,2BAAsB,GAAG,IAAI,GAAG,EAAuB,CAAC;QACxD,uBAAkB,GAAG,IAAI,GAAG,EAAuB,CAAC;QACpD,oCAA+B,GAAG,IAAI,GAAG,EAAU,CAAC;IAmItE,CAAC;IAjIA,kBAAkB,CAAC,EAAU,EAAE,UAAwC;QACtE,MAAM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B,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;YAAE,IAAI,MAAM,CAAC,QAAQ;gBAAE,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAClH,CAAC;CACD","sourcesContent":["import { SocketEventSinkActor } from \"./socket-event-fanout.ts\";\n\nexport type RawWriter = (chunk: string) => void;\nexport type BackpressureWaiter = () => Promise<void>;\n\nexport interface SessionEventWriterConnection {\n\treadonly writeRaw: RawWriter;\n\treadonly waitForBackpressure: BackpressureWaiter;\n}\n\nexport const RENDERED_COMPONENT_RECORD = \"__senpiRenderedComponent\";\n\ntype RegisteredConnection = {\n\treadonly connection: SessionEventWriterConnection;\n\treadonly actor: SocketEventSinkActor;\n};\n\ntype SnapshotRecord = { readonly line: string; readonly rendered: boolean };\n\nexport class SessionEventFanout {\n\tprivate readonly connections = new Map<string, RegisteredConnection>();\n\tprivate readonly sessionSnapshots = new Map<string, SnapshotRecord[]>();\n\tprivate readonly connectionCapabilities = new Map<string, Set<string>>();\n\tprivate readonly connectionSessions = new Map<string, Set<string>>();\n\tprivate readonly registeredCapabilityConnections = new Set<string>();\n\n\tregisterConnection(id: string, connection: SessionEventWriterConnection): void {\n\t\tconst actor = new SocketEventSinkActor(connection, () => {\n\t\t\tif (this.connections.get(id)?.actor === actor) {\n\t\t\t\tthis.connections.delete(id);\n\t\t\t\tthis.connectionCapabilities.delete(id);\n\t\t\t\tthis.connectionSessions.delete(id);\n\t\t\t\tthis.registeredCapabilityConnections.delete(id);\n\t\t\t}\n\t\t});\n\t\tthis.connections.set(id, { connection, actor });\n\t\tthis.connectionCapabilities.set(id, new Set());\n\t\tthis.connectionSessions.set(id, new Set());\n\t}\n\n\tunregisterConnection(id: string): void {\n\t\tconst registered = this.connections.get(id);\n\t\tif (!registered) return;\n\t\tregistered.actor.close();\n\t\tthis.connections.delete(id);\n\t\tthis.connectionCapabilities.delete(id);\n\t\tthis.connectionSessions.delete(id);\n\t\tthis.registeredCapabilityConnections.delete(id);\n\t}\n\n\tattachConnectionToSession(id: string, sessionId: string): void {\n\t\tif (!this.connections.has(id)) return;\n\t\tconst sessions = this.connectionSessions.get(id) ?? new Set<string>();\n\t\tif (sessions.has(sessionId)) return;\n\t\tsessions.add(sessionId);\n\t\tthis.connectionSessions.set(id, sessions);\n\t\tthis.replaySnapshot(id, sessionId);\n\t}\n\n\tdetachConnectionFromSession(id: string, sessionId: string): void {\n\t\tthis.connectionSessions.get(id)?.delete(sessionId);\n\t}\n\n\tsetConnectionCapabilities(id: string, capabilities: readonly string[]): void {\n\t\tconst registered = this.connections.get(id);\n\t\tif (!registered) return;\n\t\tconst wasCapable = this.connectionCapabilities.get(id)?.has(\"rendered_components\") ?? false;\n\t\tthis.connectionCapabilities.set(id, new Set(capabilities));\n\t\tthis.registeredCapabilityConnections.add(id);\n\t\tif (!wasCapable && capabilities.includes(\"rendered_components\"))\n\t\t\tfor (const sessionId of this.connectionSessions.get(id) ?? []) this.replayRendered(id, sessionId);\n\t}\n\n\tclearConnectionCapabilities(id: string): void {\n\t\tif (this.connections.has(id)) {\n\t\t\tthis.connectionCapabilities.set(id, new Set());\n\t\t\tthis.registeredCapabilityConnections.delete(id);\n\t\t}\n\t}\n\n\thasRegisteredConnectionCapabilities(id: string): boolean {\n\t\treturn this.registeredCapabilityConnections.has(id);\n\t}\n\n\tgetConnectionCapabilities(id: string): readonly string[] | undefined {\n\t\tif (!this.registeredCapabilityConnections.has(id)) return undefined;\n\t\treturn [...(this.connectionCapabilities.get(id) ?? [])];\n\t}\n\n\thasCapableConnection(sessionId: string): boolean {\n\t\tfor (const [id, capabilities] of this.connectionCapabilities)\n\t\t\tif (capabilities.has(\"rendered_components\") && this.connectionSessions.get(id)?.has(sessionId)) return true;\n\t\treturn false;\n\t}\n\n\ttargets(\n\t\tsessionId: string,\n\t\ttargetId: string | undefined,\n\t\tisTargeted: boolean,\n\t\trendered: boolean,\n\t): readonly (string | undefined)[] {\n\t\tif (isTargeted) return [targetId];\n\t\tif (rendered)\n\t\t\treturn this.connections.size > 0\n\t\t\t\t? [...this.connections.keys()].filter(\n\t\t\t\t\t\t(id) =>\n\t\t\t\t\t\t\tthis.connectionCapabilities.get(id)?.has(\"rendered_components\") &&\n\t\t\t\t\t\t\tthis.connectionSessions.get(id)?.has(sessionId),\n\t\t\t\t\t)\n\t\t\t\t: [undefined];\n\t\treturn this.connections.size > 0\n\t\t\t? [...this.connections.keys()].filter((id) => this.connectionSessions.get(id)?.has(sessionId))\n\t\t\t: [undefined];\n\t}\n\n\tget(id: string): RegisteredConnection | undefined {\n\t\treturn this.connections.get(id);\n\t}\n\n\tvalues(): IterableIterator<RegisteredConnection> {\n\t\treturn this.connections.values();\n\t}\n\n\tbroadcast(line: string): void {\n\t\tfor (const { actor } of this.connections.values()) actor.enqueue(line);\n\t}\n\n\trememberSnapshot(sessionId: string, value: Record<string, unknown>, line: string): void {\n\t\tconst event = value.assistantMessageEvent as Record<string, unknown> | undefined;\n\t\tconst record = { line, rendered: value[RENDERED_COMPONENT_RECORD] === true };\n\t\tif (value.type === \"message_start\" || (value.type === \"message_update\" && event?.type === \"text_start\")) {\n\t\t\tthis.sessionSnapshots.set(sessionId, [record]);\n\t\t} else if (this.sessionSnapshots.has(sessionId)) {\n\t\t\tthis.sessionSnapshots.get(sessionId)?.push(record);\n\t\t}\n\t\tif (value.type === \"message_end\") this.sessionSnapshots.delete(sessionId);\n\t}\n\n\tforgetSession(sessionId: string): void {\n\t\tthis.sessionSnapshots.delete(sessionId);\n\t}\n\n\tprivate replaySnapshot(id: string, sessionId: string): void {\n\t\tconst actor = this.connections.get(id)?.actor;\n\t\tif (!actor) return;\n\t\tconst capable = this.connectionCapabilities.get(id)?.has(\"rendered_components\") ?? false;\n\t\tfor (const record of this.sessionSnapshots.get(sessionId) ?? [])\n\t\t\tif (!record.rendered || capable) actor.enqueue(record.line);\n\t}\n\n\tprivate replayRendered(id: string, sessionId: string): void {\n\t\tconst actor = this.connections.get(id)?.actor;\n\t\tif (!actor) return;\n\t\tfor (const record of this.sessionSnapshots.get(sessionId) ?? []) if (record.rendered) actor.enqueue(record.line);\n\t}\n}\n"]}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { type SessionEventWriterConnection } from "./session-event-fanout.ts";
|
|
2
|
+
export { RENDERED_COMPONENT_RECORD, type SessionEventWriterConnection } from "./session-event-fanout.ts";
|
|
1
3
|
type RawWriter = (chunk: string) => void;
|
|
2
4
|
type BackpressureWaiter = () => Promise<void>;
|
|
3
5
|
type FlushScheduler = (flush: () => Promise<void>) => void;
|
|
@@ -10,19 +12,10 @@ type FlushScheduler = (flush: () => Promise<void>) => void;
|
|
|
10
12
|
* by itself: coalescing records from different sessions would obscure the
|
|
11
13
|
* scheduling boundary and violate D9.
|
|
12
14
|
*/
|
|
13
|
-
export interface SessionEventWriterConnection {
|
|
14
|
-
readonly writeRaw: RawWriter;
|
|
15
|
-
readonly waitForBackpressure: BackpressureWaiter;
|
|
16
|
-
}
|
|
17
|
-
export declare const RENDERED_COMPONENT_RECORD = "__senpiRenderedComponent";
|
|
18
15
|
export declare class SessionEventWriter {
|
|
19
16
|
private readonly queues;
|
|
20
|
-
private readonly
|
|
21
|
-
private readonly sessionSnapshots;
|
|
17
|
+
private readonly fanout;
|
|
22
18
|
private readonly connectionContext;
|
|
23
|
-
private readonly connectionCapabilities;
|
|
24
|
-
private readonly connectionSessions;
|
|
25
|
-
private readonly registeredCapabilityConnections;
|
|
26
19
|
private readonly controlQueue;
|
|
27
20
|
private readonly readyQueues;
|
|
28
21
|
private readonly sealedSessions;
|
|
@@ -50,7 +43,7 @@ export declare class SessionEventWriter {
|
|
|
50
43
|
withConnection<T>(id: string, task: () => T): T;
|
|
51
44
|
/** Connection id of the command currently being dispatched, when one owns it. */
|
|
52
45
|
currentConnection(): string | undefined;
|
|
53
|
-
/** Queue a session record.
|
|
46
|
+
/** Queue a session record. Content events target connections attached to the session. */
|
|
54
47
|
enqueue(sessionId: string, value: object): boolean;
|
|
55
48
|
/** Queue one untagged host-control response for the current connection. */
|
|
56
49
|
enqueueControl(value: object): Promise<void>;
|
|
@@ -71,7 +64,6 @@ export declare class SessionEventWriter {
|
|
|
71
64
|
flush(): Promise<void>;
|
|
72
65
|
private drainUntilEmpty;
|
|
73
66
|
private drainReadyQueues;
|
|
74
|
-
private rememberSnapshot;
|
|
75
67
|
private connectionQueue;
|
|
76
68
|
private appendSessionRecord;
|
|
77
69
|
private demoteAndMerge;
|
|
@@ -82,5 +74,4 @@ export declare class SessionEventWriter {
|
|
|
82
74
|
private fail;
|
|
83
75
|
private allQueues;
|
|
84
76
|
}
|
|
85
|
-
export {};
|
|
86
77
|
//# sourceMappingURL=session-event-writer.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-event-writer.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/session-event-writer.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"session-event-writer.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/session-event-writer.ts"],"names":[],"mappings":"AAEA,OAAO,EAGN,KAAK,4BAA4B,EACjC,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,yBAAyB,EAAE,KAAK,4BAA4B,EAAE,MAAM,2BAA2B,CAAC;AAEzG,KAAK,SAAS,GAAG,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;AACzC,KAAK,kBAAkB,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;AAC9C,KAAK,cAAc,GAAG,CAAC,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC;AAmD3D;;;;;;;;GAQG;AACH,qBAAa,kBAAkB;IAC9B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAkC;IACzD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA4B;IACnD,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAmC;IACrE,OAAO,CAAC,QAAQ,CAAC,YAAY,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CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC;IAI/C,iFAAiF;IACjF,iBAAiB,IAAI,MAAM,GAAG,SAAS;IAIvC,yFAAyF;IACzF,OAAO,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO;IAyBlD,2EAA2E;IAC3E,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiB5C;;;;OAIG;IACH,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;IAavD;;;;;OAKG;IACH,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IAKtC,kEAAkE;IAClE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;YA2BR,eAAe;YAOf,gBAAgB;IAuC9B,OAAO,CAAC,eAAe;IAUvB,OAAO,CAAC,mBAAmB;IAoC3B,OAAO,CAAC,cAAc;IA2BtB,OAAO,CAAC,MAAM;IAcd,OAAO,CAAC,MAAM;IAUd,OAAO,CAAC,SAAS;IAMjB,OAAO,CAAC,YAAY;IAMpB,OAAO,CAAC,IAAI;IAQZ,OAAO,CAAE,SAAS;CAIlB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
import { serializeJsonLine } from "./jsonl.js";
|
|
3
|
-
import {
|
|
3
|
+
import { RENDERED_COMPONENT_RECORD, SessionEventFanout, } from "./session-event-fanout.js";
|
|
4
|
+
export { RENDERED_COMPONENT_RECORD } from "./session-event-fanout.js";
|
|
4
5
|
const MESSAGE_KEY = "message";
|
|
5
6
|
const COMPACT_DELTA_TYPES = new Set(["text_delta", "thinking_delta", "toolcall_delta"]);
|
|
6
7
|
function compactDelta(value) {
|
|
@@ -27,16 +28,20 @@ function toolUpdateKey(value) {
|
|
|
27
28
|
? `tool:${value.toolCallId}`
|
|
28
29
|
: undefined;
|
|
29
30
|
}
|
|
30
|
-
|
|
31
|
+
/**
|
|
32
|
+
* Process-wide stdout scheduler for multi-session RPC mode.
|
|
33
|
+
*
|
|
34
|
+
* Each queue contains complete structured JSONL records for one routing handle.
|
|
35
|
+
* Draining takes one record per queue in round-robin order and waits for stdout
|
|
36
|
+
* backpressure before selecting the next one. A record is deliberately written
|
|
37
|
+
* by itself: coalescing records from different sessions would obscure the
|
|
38
|
+
* scheduling boundary and violate D9.
|
|
39
|
+
*/
|
|
31
40
|
export class SessionEventWriter {
|
|
32
41
|
constructor(writeRaw, waitOrSchedule, scheduleFlush) {
|
|
33
42
|
this.queues = new Map();
|
|
34
|
-
this.
|
|
35
|
-
this.sessionSnapshots = new Map();
|
|
43
|
+
this.fanout = new SessionEventFanout();
|
|
36
44
|
this.connectionContext = new AsyncLocalStorage();
|
|
37
|
-
this.connectionCapabilities = new Map();
|
|
38
|
-
this.connectionSessions = new Map();
|
|
39
|
-
this.registeredCapabilityConnections = new Set();
|
|
40
45
|
this.controlQueue = { latestByKey: new Map(), ready: false };
|
|
41
46
|
this.readyQueues = [];
|
|
42
47
|
this.sealedSessions = new Set();
|
|
@@ -68,78 +73,31 @@ export class SessionEventWriter {
|
|
|
68
73
|
return bytes;
|
|
69
74
|
}
|
|
70
75
|
registerConnection(id, connection) {
|
|
71
|
-
|
|
72
|
-
if (this.connections.get(id)?.actor === actor) {
|
|
73
|
-
this.connections.delete(id);
|
|
74
|
-
this.connectionCapabilities.delete(id);
|
|
75
|
-
this.connectionSessions.delete(id);
|
|
76
|
-
this.registeredCapabilityConnections.delete(id);
|
|
77
|
-
}
|
|
78
|
-
});
|
|
79
|
-
this.connections.set(id, { connection, actor });
|
|
80
|
-
this.connectionCapabilities.set(id, new Set());
|
|
81
|
-
this.connectionSessions.set(id, new Set());
|
|
82
|
-
for (const snapshot of this.sessionSnapshots.values())
|
|
83
|
-
for (const record of snapshot)
|
|
84
|
-
if (!record.rendered)
|
|
85
|
-
actor.enqueue(record.line);
|
|
76
|
+
this.fanout.registerConnection(id, connection);
|
|
86
77
|
}
|
|
87
78
|
unregisterConnection(id) {
|
|
88
|
-
|
|
89
|
-
if (!registered)
|
|
90
|
-
return;
|
|
91
|
-
registered.actor.close();
|
|
92
|
-
this.connections.delete(id);
|
|
93
|
-
this.connectionCapabilities.delete(id);
|
|
94
|
-
this.connectionSessions.delete(id);
|
|
95
|
-
this.registeredCapabilityConnections.delete(id);
|
|
79
|
+
this.fanout.unregisterConnection(id);
|
|
96
80
|
}
|
|
97
81
|
attachConnectionToSession(id, sessionId) {
|
|
98
|
-
|
|
99
|
-
return;
|
|
100
|
-
const sessions = this.connectionSessions.get(id) ?? new Set();
|
|
101
|
-
sessions.add(sessionId);
|
|
102
|
-
this.connectionSessions.set(id, sessions);
|
|
103
|
-
if (this.connectionCapabilities.get(id)?.has("rendered_components"))
|
|
104
|
-
for (const record of this.sessionSnapshots.get(sessionId) ?? [])
|
|
105
|
-
if (record.rendered)
|
|
106
|
-
this.connections.get(id).actor.enqueue(record.line);
|
|
82
|
+
this.fanout.attachConnectionToSession(id, sessionId);
|
|
107
83
|
}
|
|
108
84
|
detachConnectionFromSession(id, sessionId) {
|
|
109
|
-
this.
|
|
85
|
+
this.fanout.detachConnectionFromSession(id, sessionId);
|
|
110
86
|
}
|
|
111
87
|
setConnectionCapabilities(id, capabilities) {
|
|
112
|
-
|
|
113
|
-
if (!registered)
|
|
114
|
-
return;
|
|
115
|
-
const wasCapable = this.connectionCapabilities.get(id)?.has("rendered_components") ?? false;
|
|
116
|
-
this.connectionCapabilities.set(id, new Set(capabilities));
|
|
117
|
-
this.registeredCapabilityConnections.add(id);
|
|
118
|
-
if (!wasCapable && capabilities.includes("rendered_components"))
|
|
119
|
-
for (const sessionId of this.connectionSessions.get(id) ?? [])
|
|
120
|
-
for (const record of this.sessionSnapshots.get(sessionId) ?? [])
|
|
121
|
-
if (record.rendered)
|
|
122
|
-
registered.actor.enqueue(record.line);
|
|
88
|
+
this.fanout.setConnectionCapabilities(id, capabilities);
|
|
123
89
|
}
|
|
124
90
|
clearConnectionCapabilities(id) {
|
|
125
|
-
|
|
126
|
-
this.connectionCapabilities.set(id, new Set());
|
|
127
|
-
this.registeredCapabilityConnections.delete(id);
|
|
128
|
-
}
|
|
91
|
+
this.fanout.clearConnectionCapabilities(id);
|
|
129
92
|
}
|
|
130
93
|
hasRegisteredConnectionCapabilities(id) {
|
|
131
|
-
return this.
|
|
94
|
+
return this.fanout.hasRegisteredConnectionCapabilities(id);
|
|
132
95
|
}
|
|
133
96
|
getConnectionCapabilities(id) {
|
|
134
|
-
|
|
135
|
-
return undefined;
|
|
136
|
-
return [...(this.connectionCapabilities.get(id) ?? [])];
|
|
97
|
+
return this.fanout.getConnectionCapabilities(id);
|
|
137
98
|
}
|
|
138
99
|
hasCapableConnection(sessionId) {
|
|
139
|
-
|
|
140
|
-
if (capabilities.has("rendered_components") && this.connectionSessions.get(id)?.has(sessionId))
|
|
141
|
-
return true;
|
|
142
|
-
return false;
|
|
100
|
+
return this.fanout.hasCapableConnection(sessionId);
|
|
143
101
|
}
|
|
144
102
|
/** Execute a connection's command with its response destination in context. */
|
|
145
103
|
withConnection(id, task) {
|
|
@@ -149,7 +107,7 @@ export class SessionEventWriter {
|
|
|
149
107
|
currentConnection() {
|
|
150
108
|
return this.connectionContext.getStore();
|
|
151
109
|
}
|
|
152
|
-
/** Queue a session record.
|
|
110
|
+
/** Queue a session record. Content events target connections attached to the session. */
|
|
153
111
|
enqueue(sessionId, value) {
|
|
154
112
|
if (this.sealedSessions.has(sessionId))
|
|
155
113
|
return false;
|
|
@@ -162,19 +120,13 @@ export class SessionEventWriter {
|
|
|
162
120
|
const tagged = { ...value, sessionId };
|
|
163
121
|
const { [RENDERED_COMPONENT_RECORD]: _rendered, ...wireTagged } = tagged;
|
|
164
122
|
const line = serializeJsonLine(wireTagged);
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
: record[RENDERED_COMPONENT_RECORD] && this.connections.size > 0
|
|
169
|
-
? [...this.connections.keys()].filter((id) => this.connectionCapabilities.get(id)?.has("rendered_components") &&
|
|
170
|
-
this.connectionSessions.get(id)?.has(sessionId))
|
|
171
|
-
: this.connections.size > 0
|
|
172
|
-
? [...this.connections.keys()]
|
|
173
|
-
: [undefined];
|
|
123
|
+
if (!isTargeted)
|
|
124
|
+
this.fanout.rememberSnapshot(sessionId, tagged, line);
|
|
125
|
+
const targets = this.fanout.targets(sessionId, targetId, isTargeted, record[RENDERED_COMPONENT_RECORD] === true);
|
|
174
126
|
for (const target of targets) {
|
|
175
|
-
if (target !== undefined && !this.
|
|
127
|
+
if (target !== undefined && !this.fanout.get(target))
|
|
176
128
|
continue;
|
|
177
|
-
const registered = target === undefined ? undefined : this.
|
|
129
|
+
const registered = target === undefined ? undefined : this.fanout.get(target);
|
|
178
130
|
if (registered)
|
|
179
131
|
registered.actor.enqueue(line, compactDelta(tagged) && tagged.message !== null ? MESSAGE_KEY : undefined);
|
|
180
132
|
else
|
|
@@ -188,7 +140,7 @@ export class SessionEventWriter {
|
|
|
188
140
|
if (this.failure !== undefined)
|
|
189
141
|
return Promise.reject(this.failure);
|
|
190
142
|
const targetId = this.connectionContext.getStore();
|
|
191
|
-
const registered = targetId === undefined ? undefined : this.
|
|
143
|
+
const registered = targetId === undefined ? undefined : this.fanout.get(targetId);
|
|
192
144
|
if (registered) {
|
|
193
145
|
registered.actor.enqueue(serializeJsonLine(value));
|
|
194
146
|
return Promise.resolve();
|
|
@@ -212,11 +164,9 @@ export class SessionEventWriter {
|
|
|
212
164
|
this.sealedSessions.add(sessionId);
|
|
213
165
|
const targetId = this.connectionContext.getStore();
|
|
214
166
|
const lifecycle = { type: "session_closed", sessionId };
|
|
215
|
-
|
|
216
|
-
this.connections.get(connectionId).actor.enqueue(serializeJsonLine(lifecycle));
|
|
217
|
-
}
|
|
167
|
+
this.fanout.broadcast(serializeJsonLine(lifecycle));
|
|
218
168
|
const taggedResponse = { ...response, sessionId };
|
|
219
|
-
const registered = targetId === undefined ? undefined : this.
|
|
169
|
+
const registered = targetId === undefined ? undefined : this.fanout.get(targetId);
|
|
220
170
|
if (registered)
|
|
221
171
|
registered.actor.enqueue(serializeJsonLine(taggedResponse));
|
|
222
172
|
else
|
|
@@ -231,7 +181,7 @@ export class SessionEventWriter {
|
|
|
231
181
|
*/
|
|
232
182
|
forgetSession(sessionId) {
|
|
233
183
|
this.sealedSessions.delete(sessionId);
|
|
234
|
-
this.
|
|
184
|
+
this.fanout.forgetSession(sessionId);
|
|
235
185
|
}
|
|
236
186
|
/** Drain every retained lane and the current in-flight record. */
|
|
237
187
|
flush() {
|
|
@@ -241,7 +191,7 @@ export class SessionEventWriter {
|
|
|
241
191
|
if (this.drainPromise)
|
|
242
192
|
return this.drainPromise;
|
|
243
193
|
if (this.readyQueues.length === 0)
|
|
244
|
-
return Promise.all([...this.
|
|
194
|
+
return Promise.all([...this.fanout.values()].map(({ actor }) => actor.flush())).then(() => undefined);
|
|
245
195
|
let resolveDrain;
|
|
246
196
|
let rejectDrain;
|
|
247
197
|
const drain = new Promise((resolve, reject) => {
|
|
@@ -266,7 +216,7 @@ export class SessionEventWriter {
|
|
|
266
216
|
do {
|
|
267
217
|
await this.drainReadyQueues();
|
|
268
218
|
} while (this.readyQueues.length > 0);
|
|
269
|
-
await Promise.all([...this.
|
|
219
|
+
await Promise.all([...this.fanout.values()].map(({ actor }) => actor.flush()));
|
|
270
220
|
}
|
|
271
221
|
async drainReadyQueues() {
|
|
272
222
|
while (this.readyQueues.length > 0) {
|
|
@@ -280,7 +230,7 @@ export class SessionEventWriter {
|
|
|
280
230
|
try {
|
|
281
231
|
// D9: exactly one complete record per raw write. The next lane is not
|
|
282
232
|
// selected until this record has cleared stdout backpressure.
|
|
283
|
-
const connection = queue.targetId ? this.
|
|
233
|
+
const connection = queue.targetId ? this.fanout.get(queue.targetId)?.connection : undefined;
|
|
284
234
|
const writeRaw = connection?.writeRaw ?? this.writeRaw;
|
|
285
235
|
const waitForBackpressure = connection?.waitForBackpressure ?? this.waitForBackpressure;
|
|
286
236
|
if (!connection && queue.targetId) {
|
|
@@ -311,18 +261,6 @@ export class SessionEventWriter {
|
|
|
311
261
|
}
|
|
312
262
|
}
|
|
313
263
|
}
|
|
314
|
-
rememberSnapshot(sessionId, value, line) {
|
|
315
|
-
const event = value.assistantMessageEvent;
|
|
316
|
-
const record = { line, rendered: value[RENDERED_COMPONENT_RECORD] === true };
|
|
317
|
-
if (value.type === "message_start" || (value.type === "message_update" && event?.type === "text_start")) {
|
|
318
|
-
this.sessionSnapshots.set(sessionId, [record]);
|
|
319
|
-
}
|
|
320
|
-
else if (this.sessionSnapshots.has(sessionId)) {
|
|
321
|
-
this.sessionSnapshots.get(sessionId).push(record);
|
|
322
|
-
}
|
|
323
|
-
if (value.type === "message_end")
|
|
324
|
-
this.sessionSnapshots.delete(sessionId);
|
|
325
|
-
}
|
|
326
264
|
connectionQueue(targetId) {
|
|
327
265
|
const key = `connection:${targetId}`;
|
|
328
266
|
let queue = this.queues.get(key);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-event-writer.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-event-writer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AA0BhE,MAAM,WAAW,GAAG,SAAS,CAAC;AAC9B,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAmB,CAAC,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,CAAC,CAAC,CAAC;AAE1G,SAAS,YAAY,CAAC,KAAgB;IACrC,IAAI,KAAK,CAAC,IAAI,KAAK,gBAAgB,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,SAAS,CAAC;QAAE,OAAO,SAAS,CAAC;I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AAC;IAEO,YAAY;QACnB,IAAI,IAAI,CAAC,OAAO,KAAK,SAAS,IAAI,IAAI,CAAC,cAAc,IAAI,IAAI,CAAC,YAAY;YAAE,OAAO;QACnF,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;QAC3B,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;IACxC,CAAC;IAEO,IAAI,CAAC,KAAc;QAC1B,IAAI,IAAI,CAAC,OAAO,KAAK,SAAS;YAAE,OAAO;QACvC,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QACrB,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YACtC,KAAK,IAAI,IAAI,GAAG,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC,IAAI;gBAAE,IAAI,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC;QAC1E,CAAC;IACF,CAAC;IAEO,CAAC,SAAS;QACjB,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;QAC5B,MAAM,IAAI,CAAC,YAAY,CAAC;IACzB,CAAC;CACD","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { serializeJsonLine } from \"./jsonl.ts\";\nimport { SocketEventSinkActor } from \"./socket-event-fanout.ts\";\n\ntype RawWriter = (chunk: string) => void;\ntype BackpressureWaiter = () => Promise<void>;\ntype FlushScheduler = (flush: () => Promise<void>) => void;\ntype RpcRecord = Record<string, unknown>;\ntype CompactDeltaType = \"text_delta\" | \"thinking_delta\" | \"toolcall_delta\";\n\ntype QueueNode = {\n\tvalue: RpcRecord;\n\tkey?: string;\n\tprevious?: QueueNode;\n\tnext?: QueueNode;\n\tresolve?: () => void;\n\treject?: (cause: unknown) => void;\n};\n\ntype RecordQueue = {\n\tsessionId?: string;\n\ttargetId?: string;\n\thead?: QueueNode;\n\ttail?: QueueNode;\n\tlatestByKey: Map<string, QueueNode>;\n\tready: boolean;\n};\n\nconst MESSAGE_KEY = \"message\";\nconst COMPACT_DELTA_TYPES = new Set<CompactDeltaType>([\"text_delta\", \"thinking_delta\", \"toolcall_delta\"]);\n\nfunction compactDelta(value: RpcRecord): { type: CompactDeltaType; contentIndex: number; delta: string } | undefined {\n\tif (value.type !== \"message_update\" || !Object.hasOwn(value, \"message\")) return undefined;\n\tconst event = value.assistantMessageEvent;\n\tif (typeof event !== \"object\" || event === null) return undefined;\n\tconst typedEvent = event as Record<string, unknown>;\n\tif (\n\t\ttypeof typedEvent.type !== \"string\" ||\n\t\t!COMPACT_DELTA_TYPES.has(typedEvent.type as CompactDeltaType) ||\n\t\ttypeof typedEvent.contentIndex !== \"number\" ||\n\t\ttypeof typedEvent.delta !== \"string\"\n\t) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\ttype: typedEvent.type as CompactDeltaType,\n\t\tcontentIndex: typedEvent.contentIndex,\n\t\tdelta: typedEvent.delta,\n\t};\n}\n\nfunction toolUpdateKey(value: RpcRecord): string | undefined {\n\treturn value.type === \"tool_execution_update\" && typeof value.toolCallId === \"string\"\n\t\t? `tool:${value.toolCallId}`\n\t\t: undefined;\n}\n\n/**\n * Process-wide stdout scheduler for multi-session RPC mode.\n *\n * Each queue contains complete structured JSONL records for one routing handle.\n * Draining takes one record per queue in round-robin order and waits for stdout\n * backpressure before selecting the next one. A record is deliberately written\n * by itself: coalescing records from different sessions would obscure the\n * scheduling boundary and violate D9.\n */\nexport interface SessionEventWriterConnection {\n\treadonly writeRaw: RawWriter;\n\treadonly waitForBackpressure: BackpressureWaiter;\n}\n\nexport const RENDERED_COMPONENT_RECORD = \"__senpiRenderedComponent\";\n\nexport class SessionEventWriter {\n\tprivate readonly queues = new Map<string, RecordQueue>();\n\tprivate readonly connections = new Map<\n\t\tstring,\n\t\t{ connection: SessionEventWriterConnection; actor: SocketEventSinkActor }\n\t>();\n\tprivate readonly sessionSnapshots = new Map<string, Array<{ line: string; rendered: boolean }>>();\n\tprivate readonly connectionContext = new AsyncLocalStorage<string>();\n\tprivate readonly connectionCapabilities = new Map<string, Set<string>>();\n\tprivate readonly connectionSessions = new Map<string, Set<string>>();\n\tprivate readonly registeredCapabilityConnections = new Set<string>();\n\tprivate readonly controlQueue: RecordQueue = { latestByKey: new Map(), ready: false };\n\tprivate readonly readyQueues: RecordQueue[] = [];\n\tprivate readonly sealedSessions = new Set<string>();\n\tprivate readonly writeRaw: RawWriter;\n\tprivate readonly waitForBackpressure?: BackpressureWaiter;\n\tprivate readonly scheduleFlush: FlushScheduler;\n\tprivate flushScheduled = false;\n\tprivate drainPromise?: Promise<void>;\n\tprivate inFlight?: { queue: RecordQueue; node: QueueNode };\n\tprivate failure?: unknown;\n\n\tconstructor(writeRaw: RawWriter, scheduleFlush?: FlushScheduler);\n\tconstructor(writeRaw: RawWriter, waitForBackpressure: BackpressureWaiter, scheduleFlush?: FlushScheduler);\n\tconstructor(\n\t\twriteRaw: RawWriter,\n\t\twaitOrSchedule?: BackpressureWaiter | FlushScheduler,\n\t\tscheduleFlush?: FlushScheduler,\n\t) {\n\t\tthis.writeRaw = writeRaw;\n\t\tif (waitOrSchedule && scheduleFlush === undefined && waitOrSchedule.length > 0) {\n\t\t\tthis.scheduleFlush = waitOrSchedule as FlushScheduler;\n\t\t} else {\n\t\t\tthis.waitForBackpressure = waitOrSchedule as BackpressureWaiter | undefined;\n\t\t\tthis.scheduleFlush = scheduleFlush ?? ((flush) => queueMicrotask(() => void flush()));\n\t\t}\n\t}\n\n\tget bufferedRecordCount(): number {\n\t\tlet count = this.inFlight ? 1 : 0;\n\t\tfor (const queue of this.allQueues()) {\n\t\t\tfor (let node = queue.head; node; node = node.next) count++;\n\t\t}\n\t\treturn count;\n\t}\n\n\tget bufferedByteLength(): number {\n\t\tlet bytes = this.inFlight ? Buffer.byteLength(serializeJsonLine(this.inFlight.node.value)) : 0;\n\t\tfor (const queue of this.allQueues()) {\n\t\t\tfor (let node = queue.head; node; node = node.next) {\n\t\t\t\tbytes += Buffer.byteLength(serializeJsonLine(node.value));\n\t\t\t}\n\t\t}\n\t\treturn bytes;\n\t}\n\n\tregisterConnection(id: string, connection: SessionEventWriterConnection): void {\n\t\tconst actor = new SocketEventSinkActor(connection, () => {\n\t\t\tif (this.connections.get(id)?.actor === actor) {\n\t\t\t\tthis.connections.delete(id);\n\t\t\t\tthis.connectionCapabilities.delete(id);\n\t\t\t\tthis.connectionSessions.delete(id);\n\t\t\t\tthis.registeredCapabilityConnections.delete(id);\n\t\t\t}\n\t\t});\n\t\tthis.connections.set(id, { connection, actor });\n\t\tthis.connectionCapabilities.set(id, new Set());\n\t\tthis.connectionSessions.set(id, new Set());\n\t\tfor (const snapshot of this.sessionSnapshots.values())\n\t\t\tfor (const record of snapshot) if (!record.rendered) actor.enqueue(record.line);\n\t}\n\n\tunregisterConnection(id: string): void {\n\t\tconst registered = this.connections.get(id);\n\t\tif (!registered) return;\n\t\tregistered.actor.close();\n\t\tthis.connections.delete(id);\n\t\tthis.connectionCapabilities.delete(id);\n\t\tthis.connectionSessions.delete(id);\n\t\tthis.registeredCapabilityConnections.delete(id);\n\t}\n\n\tattachConnectionToSession(id: string, sessionId: string): void {\n\t\tif (!this.connections.has(id)) return;\n\t\tconst sessions = this.connectionSessions.get(id) ?? new Set<string>();\n\t\tsessions.add(sessionId);\n\t\tthis.connectionSessions.set(id, sessions);\n\t\tif (this.connectionCapabilities.get(id)?.has(\"rendered_components\"))\n\t\t\tfor (const record of this.sessionSnapshots.get(sessionId) ?? [])\n\t\t\t\tif (record.rendered) this.connections.get(id)!.actor.enqueue(record.line);\n\t}\n\n\tdetachConnectionFromSession(id: string, sessionId: string): void {\n\t\tthis.connectionSessions.get(id)?.delete(sessionId);\n\t}\n\n\tsetConnectionCapabilities(id: string, capabilities: readonly string[]): void {\n\t\tconst registered = this.connections.get(id);\n\t\tif (!registered) return;\n\t\tconst wasCapable = this.connectionCapabilities.get(id)?.has(\"rendered_components\") ?? false;\n\t\tthis.connectionCapabilities.set(id, new Set(capabilities));\n\t\tthis.registeredCapabilityConnections.add(id);\n\t\tif (!wasCapable && capabilities.includes(\"rendered_components\"))\n\t\t\tfor (const sessionId of this.connectionSessions.get(id) ?? [])\n\t\t\t\tfor (const record of this.sessionSnapshots.get(sessionId) ?? [])\n\t\t\t\t\tif (record.rendered) registered.actor.enqueue(record.line);\n\t}\n\n\tclearConnectionCapabilities(id: string): void {\n\t\tif (this.connections.has(id)) {\n\t\t\tthis.connectionCapabilities.set(id, new Set());\n\t\t\tthis.registeredCapabilityConnections.delete(id);\n\t\t}\n\t}\n\n\thasRegisteredConnectionCapabilities(id: string): boolean {\n\t\treturn this.registeredCapabilityConnections.has(id);\n\t}\n\n\tgetConnectionCapabilities(id: string): readonly string[] | undefined {\n\t\tif (!this.registeredCapabilityConnections.has(id)) return undefined;\n\t\treturn [...(this.connectionCapabilities.get(id) ?? [])];\n\t}\n\n\thasCapableConnection(sessionId: string): boolean {\n\t\tfor (const [id, capabilities] of this.connectionCapabilities)\n\t\t\tif (capabilities.has(\"rendered_components\") && this.connectionSessions.get(id)?.has(sessionId)) return true;\n\t\treturn false;\n\t}\n\n\t/** Execute a connection's command with its response destination in context. */\n\twithConnection<T>(id: string, task: () => T): T {\n\t\treturn this.connectionContext.run(id, task);\n\t}\n\n\t/** Connection id of the command currently being dispatched, when one owns it. */\n\tcurrentConnection(): string | undefined {\n\t\treturn this.connectionContext.getStore();\n\t}\n\n\t/** Queue a session record. Lifecycle/events are broadcast; responses/UI are targeted. */\n\tenqueue(sessionId: string, value: object): boolean {\n\t\tif (this.sealedSessions.has(sessionId)) return false;\n\t\tconst targetId = this.connectionContext.getStore();\n\t\tconst record = value as RpcRecord;\n\t\tconst isTargeted =\n\t\t\trecord.type === \"response\" ||\n\t\t\trecord.type === \"bash_execution_update\" ||\n\t\t\t(record.type === \"extension_ui_request\" &&\n\t\t\t\t[\"select\", \"confirm\", \"input\", \"editor\"].includes(String(record.method)));\n\t\tconst tagged = { ...value, sessionId } as RpcRecord;\n\t\tconst { [RENDERED_COMPONENT_RECORD]: _rendered, ...wireTagged } = tagged;\n\t\tconst line = serializeJsonLine(wireTagged);\n\t\tthis.rememberSnapshot(sessionId, tagged, line);\n\t\tconst targets = isTargeted\n\t\t\t? [targetId]\n\t\t\t: record[RENDERED_COMPONENT_RECORD] && this.connections.size > 0\n\t\t\t\t? [...this.connections.keys()].filter(\n\t\t\t\t\t\t(id) =>\n\t\t\t\t\t\t\tthis.connectionCapabilities.get(id)?.has(\"rendered_components\") &&\n\t\t\t\t\t\t\tthis.connectionSessions.get(id)?.has(sessionId),\n\t\t\t\t\t)\n\t\t\t\t: this.connections.size > 0\n\t\t\t\t\t? [...this.connections.keys()]\n\t\t\t\t\t: [undefined];\n\t\tfor (const target of targets) {\n\t\t\tif (target !== undefined && !this.connections.has(target)) continue;\n\t\t\tconst registered = target === undefined ? undefined : this.connections.get(target);\n\t\t\tif (registered)\n\t\t\t\tregistered.actor.enqueue(line, compactDelta(tagged) && tagged.message !== null ? MESSAGE_KEY : undefined);\n\t\t\telse this.appendSessionRecord(sessionId, wireTagged, target);\n\t\t}\n\t\tthis.requestFlush();\n\t\treturn true;\n\t}\n\n\t/** Queue one untagged host-control response for the current connection. */\n\tenqueueControl(value: object): Promise<void> {\n\t\tif (this.failure !== undefined) return Promise.reject(this.failure);\n\t\tconst targetId = this.connectionContext.getStore();\n\t\tconst registered = targetId === undefined ? undefined : this.connections.get(targetId);\n\t\tif (registered) {\n\t\t\tregistered.actor.enqueue(serializeJsonLine(value));\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tconst queue = targetId === undefined ? this.controlQueue : this.connectionQueue(targetId);\n\t\tconst completion = new Promise<void>((resolve, reject) => {\n\t\t\tthis.append(queue, { ...value }, undefined, resolve, reject);\n\t\t});\n\t\tthis.markReady(queue);\n\t\tthis.requestFlush();\n\t\treturn completion;\n\t}\n\n\t/**\n\t * Prevent subsequent records for a session and append its terminal response.\n\t * Existing records retain FIFO order; this response is therefore that\n\t * session's final stdout record.\n\t */\n\tcloseSession(sessionId: string, response: object): void {\n\t\tif (this.sealedSessions.has(sessionId)) return;\n\t\tthis.sealedSessions.add(sessionId);\n\t\tconst targetId = this.connectionContext.getStore();\n\t\tconst lifecycle = { type: \"session_closed\", sessionId };\n\t\tfor (const connectionId of this.connections.keys()) {\n\t\t\tthis.connections.get(connectionId)!.actor.enqueue(serializeJsonLine(lifecycle));\n\t\t}\n\t\tconst taggedResponse = { ...response, sessionId };\n\t\tconst registered = targetId === undefined ? undefined : this.connections.get(targetId);\n\t\tif (registered) registered.actor.enqueue(serializeJsonLine(taggedResponse));\n\t\telse this.appendSessionRecord(sessionId, taggedResponse, targetId);\n\t\tthis.requestFlush();\n\t}\n\n\t/**\n\t * Drops per-session bookkeeping for a handle whose runtime is fully disposed.\n\t * Routing handles are unique per process epoch, so nothing can legitimately\n\t * emit under this id again; without this every host-closed session would\n\t * leave a permanent sealed-handle (and snapshot) entry behind.\n\t */\n\tforgetSession(sessionId: string): void {\n\t\tthis.sealedSessions.delete(sessionId);\n\t\tthis.sessionSnapshots.delete(sessionId);\n\t}\n\n\t/** Drain every retained lane and the current in-flight record. */\n\tflush(): Promise<void> {\n\t\tif (this.failure !== undefined) return Promise.reject(this.failure);\n\t\tthis.flushScheduled = false;\n\t\tif (this.drainPromise) return this.drainPromise;\n\t\tif (this.readyQueues.length === 0)\n\t\t\treturn Promise.all([...this.connections.values()].map(({ actor }) => actor.flush())).then(() => undefined);\n\t\tlet resolveDrain!: () => void;\n\t\tlet rejectDrain!: (cause: unknown) => void;\n\t\tconst drain = new Promise<void>((resolve, reject) => {\n\t\t\tresolveDrain = resolve;\n\t\t\trejectDrain = reject;\n\t\t});\n\t\tthis.drainPromise = drain;\n\t\tvoid this.drainUntilEmpty().then(resolveDrain, rejectDrain);\n\t\tvoid drain.then(\n\t\t\t() => {\n\t\t\t\tif (this.drainPromise === drain) this.drainPromise = undefined;\n\t\t\t\tif (this.readyQueues.length > 0) this.requestFlush();\n\t\t\t},\n\t\t\t(cause) => {\n\t\t\t\tif (this.drainPromise === drain) this.drainPromise = undefined;\n\t\t\t\tthis.fail(cause);\n\t\t\t},\n\t\t);\n\t\treturn drain;\n\t}\n\n\tprivate async drainUntilEmpty(): Promise<void> {\n\t\tdo {\n\t\t\tawait this.drainReadyQueues();\n\t\t} while (this.readyQueues.length > 0);\n\t\tawait Promise.all([...this.connections.values()].map(({ actor }) => actor.flush()));\n\t}\n\n\tprivate async drainReadyQueues(): Promise<void> {\n\t\twhile (this.readyQueues.length > 0) {\n\t\t\tconst queue = this.readyQueues.shift()!;\n\t\t\tqueue.ready = false;\n\t\t\tconst node = queue.head;\n\t\t\tif (!node) continue;\n\n\t\t\tthis.unlink(queue, node);\n\t\t\tthis.inFlight = { queue, node };\n\t\t\ttry {\n\t\t\t\t// D9: exactly one complete record per raw write. The next lane is not\n\t\t\t\t// selected until this record has cleared stdout backpressure.\n\t\t\t\tconst connection = queue.targetId ? this.connections.get(queue.targetId)?.connection : undefined;\n\t\t\t\tconst writeRaw = connection?.writeRaw ?? this.writeRaw;\n\t\t\t\tconst waitForBackpressure = connection?.waitForBackpressure ?? this.waitForBackpressure;\n\t\t\t\tif (!connection && queue.targetId) {\n\t\t\t\t\tnode.resolve?.();\n\t\t\t\t} else {\n\t\t\t\t\twriteRaw(serializeJsonLine(node.value));\n\t\t\t\t\tif (waitForBackpressure) await waitForBackpressure();\n\t\t\t\t\tnode.resolve?.();\n\t\t\t\t}\n\t\t\t} catch (cause) {\n\t\t\t\tnode.reject?.(cause);\n\t\t\t\tthrow cause;\n\t\t\t} finally {\n\t\t\t\tthis.inFlight = undefined;\n\t\t\t}\n\n\t\t\tif (queue.head) {\n\t\t\t\tthis.markReady(queue);\n\t\t\t} else if (queue.sessionId || queue.targetId) {\n\t\t\t\tfor (const [key, candidate] of this.queues) {\n\t\t\t\t\tif (candidate === queue) this.queues.delete(key);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate rememberSnapshot(sessionId: string, value: RpcRecord, line: string): void {\n\t\tconst event = value.assistantMessageEvent as Record<string, unknown> | undefined;\n\t\tconst record = { line, rendered: value[RENDERED_COMPONENT_RECORD] === true };\n\t\tif (value.type === \"message_start\" || (value.type === \"message_update\" && event?.type === \"text_start\")) {\n\t\t\tthis.sessionSnapshots.set(sessionId, [record]);\n\t\t} else if (this.sessionSnapshots.has(sessionId)) {\n\t\t\tthis.sessionSnapshots.get(sessionId)!.push(record);\n\t\t}\n\t\tif (value.type === \"message_end\") this.sessionSnapshots.delete(sessionId);\n\t}\n\n\tprivate connectionQueue(targetId: string): RecordQueue {\n\t\tconst key = `connection:${targetId}`;\n\t\tlet queue = this.queues.get(key);\n\t\tif (!queue) {\n\t\t\tqueue = { targetId, latestByKey: new Map(), ready: false };\n\t\t\tthis.queues.set(key, queue);\n\t\t}\n\t\treturn queue;\n\t}\n\n\tprivate appendSessionRecord(sessionId: string, value: RpcRecord, targetId?: string): void {\n\t\tconst key = `${targetId ?? \"default\"}:${sessionId}`;\n\t\tlet queue = this.queues.get(key);\n\t\tif (!queue) {\n\t\t\tqueue = { sessionId, targetId, latestByKey: new Map(), ready: false };\n\t\t\tthis.queues.set(key, queue);\n\t\t}\n\n\t\tconst delta = compactDelta(value);\n\t\tif (delta) {\n\t\t\tconst previousFull = queue.latestByKey.get(MESSAGE_KEY);\n\t\t\tif (previousFull) this.demoteAndMerge(queue, previousFull);\n\t\t\tconst node = this.append(queue, value, MESSAGE_KEY);\n\t\t\tqueue.latestByKey.set(MESSAGE_KEY, node);\n\t\t\tthis.markReady(queue);\n\t\t\treturn;\n\t\t}\n\n\t\tconst toolKey = toolUpdateKey(value);\n\t\tif (toolKey) {\n\t\t\tconst previous = queue.latestByKey.get(toolKey);\n\t\t\tif (previous) this.unlink(queue, previous);\n\t\t\tconst node = this.append(queue, value, toolKey);\n\t\t\tqueue.latestByKey.set(toolKey, node);\n\t\t\tthis.markReady(queue);\n\t\t\treturn;\n\t\t}\n\n\t\t// All non-compactable records are ordering barriers. In particular this\n\t\t// includes delta-only/full non-delta message updates, protocol responses,\n\t\t// extension UI requests, errors, retries, lifecycle, and unknown records.\n\t\tqueue.latestByKey.clear();\n\t\tthis.append(queue, value);\n\t\tthis.markReady(queue);\n\t}\n\n\tprivate demoteAndMerge(queue: RecordQueue, node: QueueNode): void {\n\t\tconst event = node.value.assistantMessageEvent as Record<string, unknown>;\n\t\tnode.value = {\n\t\t\t...node.value,\n\t\t\tmessage: null,\n\t\t\tassistantMessageEvent: { ...event, partial: null },\n\t\t};\n\t\tconst current = compactDelta(node.value);\n\t\tconst preceding = node.previous;\n\t\tconst previous = preceding ? compactDelta(preceding.value) : undefined;\n\t\tif (\n\t\t\tpreceding &&\n\t\t\tprevious &&\n\t\t\tcurrent &&\n\t\t\tpreceding.value.message === null &&\n\t\t\tprevious.type === current.type &&\n\t\t\tprevious.contentIndex === current.contentIndex\n\t\t) {\n\t\t\tconst precedingEvent = preceding.value.assistantMessageEvent as Record<string, unknown>;\n\t\t\tpreceding.value = {\n\t\t\t\t...preceding.value,\n\t\t\t\tassistantMessageEvent: { ...precedingEvent, delta: previous.delta + current.delta },\n\t\t\t};\n\t\t\tthis.unlink(queue, node);\n\t\t}\n\t}\n\n\tprivate append(\n\t\tqueue: RecordQueue,\n\t\tvalue: RpcRecord,\n\t\tkey?: string,\n\t\tresolve?: () => void,\n\t\treject?: (cause: unknown) => void,\n\t): QueueNode {\n\t\tconst node: QueueNode = { value, key, previous: queue.tail, resolve, reject };\n\t\tif (queue.tail) queue.tail.next = node;\n\t\telse queue.head = node;\n\t\tqueue.tail = node;\n\t\treturn node;\n\t}\n\n\tprivate unlink(queue: RecordQueue, node: QueueNode): void {\n\t\tif (node.previous) node.previous.next = node.next;\n\t\telse queue.head = node.next;\n\t\tif (node.next) node.next.previous = node.previous;\n\t\telse queue.tail = node.previous;\n\t\tif (node.key && queue.latestByKey.get(node.key) === node) queue.latestByKey.delete(node.key);\n\t\tnode.previous = undefined;\n\t\tnode.next = undefined;\n\t}\n\n\tprivate markReady(queue: RecordQueue): void {\n\t\tif (queue.ready || this.inFlight?.queue === queue || !queue.head) return;\n\t\tqueue.ready = true;\n\t\tthis.readyQueues.push(queue);\n\t}\n\n\tprivate requestFlush(): void {\n\t\tif (this.failure !== undefined || this.flushScheduled || this.drainPromise) return;\n\t\tthis.flushScheduled = true;\n\t\tthis.scheduleFlush(() => this.flush());\n\t}\n\n\tprivate fail(cause: unknown): void {\n\t\tif (this.failure !== undefined) return;\n\t\tthis.failure = cause;\n\t\tfor (const queue of this.allQueues()) {\n\t\t\tfor (let node = queue.head; node; node = node.next) node.reject?.(cause);\n\t\t}\n\t}\n\n\tprivate *allQueues(): Iterable<RecordQueue> {\n\t\tyield* this.queues.values();\n\t\tyield this.controlQueue;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session-event-writer.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-event-writer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EACN,yBAAyB,EACzB,kBAAkB,GAElB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,yBAAyB,EAAqC,MAAM,2BAA2B,CAAC;AA0BzG,MAAM,WAAW,GAAG,SAAS,CAAC;AAC9B,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAmB,CAAC,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,CAAC,CAAC,CAAC;AAE1G,SAAS,YAAY,CAAC,KAAgB;IACrC,IAAI,KAAK,CAAC,IAAI,KAAK,gBAAgB,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,SAAS,CAAC;QAAE,OAAO,SAAS,CAAC;IAC1F,MAAM,KAAK,GAAG,KAAK,CAAC,qBAAqB,CAAC;IAC1C,IAAI,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AC;QAC1B,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC;IACvB,CAAC;IAEO,SAAS,CAAC,KAAkB;QACnC,IAAI,KAAK,CAAC,KAAK,IAAI,IAAI,CAAC,QAAQ,EAAE,KAAK,KAAK,KAAK,IAAI,CAAC,KAAK,CAAC,IAAI;YAAE,OAAO;QACzE,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC;QACnB,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IAEO,YAAY;QACnB,IAAI,IAAI,CAAC,OAAO,KAAK,SAAS,IAAI,IAAI,CAAC,cAAc,IAAI,IAAI,CAAC,YAAY;YAAE,OAAO;QACnF,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;QAC3B,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;IACxC,CAAC;IAEO,IAAI,CAAC,KAAc;QAC1B,IAAI,IAAI,CAAC,OAAO,KAAK,SAAS;YAAE,OAAO;QACvC,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QACrB,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YACtC,KAAK,IAAI,IAAI,GAAG,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC,IAAI;gBAAE,IAAI,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC;QAC1E,CAAC;IACF,CAAC;IAEO,CAAC,SAAS;QACjB,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;QAC5B,MAAM,IAAI,CAAC,YAAY,CAAC;IACzB,CAAC;CACD","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { serializeJsonLine } from \"./jsonl.ts\";\nimport {\n\tRENDERED_COMPONENT_RECORD,\n\tSessionEventFanout,\n\ttype SessionEventWriterConnection,\n} from \"./session-event-fanout.ts\";\n\nexport { RENDERED_COMPONENT_RECORD, type SessionEventWriterConnection } from \"./session-event-fanout.ts\";\n\ntype RawWriter = (chunk: string) => void;\ntype BackpressureWaiter = () => Promise<void>;\ntype FlushScheduler = (flush: () => Promise<void>) => void;\ntype RpcRecord = Record<string, unknown>;\ntype CompactDeltaType = \"text_delta\" | \"thinking_delta\" | \"toolcall_delta\";\n\ntype QueueNode = {\n\tvalue: RpcRecord;\n\tkey?: string;\n\tprevious?: QueueNode;\n\tnext?: QueueNode;\n\tresolve?: () => void;\n\treject?: (cause: unknown) => void;\n};\n\ntype RecordQueue = {\n\tsessionId?: string;\n\ttargetId?: string;\n\thead?: QueueNode;\n\ttail?: QueueNode;\n\tlatestByKey: Map<string, QueueNode>;\n\tready: boolean;\n};\n\nconst MESSAGE_KEY = \"message\";\nconst COMPACT_DELTA_TYPES = new Set<CompactDeltaType>([\"text_delta\", \"thinking_delta\", \"toolcall_delta\"]);\n\nfunction compactDelta(value: RpcRecord): { type: CompactDeltaType; contentIndex: number; delta: string } | undefined {\n\tif (value.type !== \"message_update\" || !Object.hasOwn(value, \"message\")) return undefined;\n\tconst event = value.assistantMessageEvent;\n\tif (typeof event !== \"object\" || event === null) return undefined;\n\tconst typedEvent = event as Record<string, unknown>;\n\tif (\n\t\ttypeof typedEvent.type !== \"string\" ||\n\t\t!COMPACT_DELTA_TYPES.has(typedEvent.type as CompactDeltaType) ||\n\t\ttypeof typedEvent.contentIndex !== \"number\" ||\n\t\ttypeof typedEvent.delta !== \"string\"\n\t) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\ttype: typedEvent.type as CompactDeltaType,\n\t\tcontentIndex: typedEvent.contentIndex,\n\t\tdelta: typedEvent.delta,\n\t};\n}\n\nfunction toolUpdateKey(value: RpcRecord): string | undefined {\n\treturn value.type === \"tool_execution_update\" && typeof value.toolCallId === \"string\"\n\t\t? `tool:${value.toolCallId}`\n\t\t: undefined;\n}\n\n/**\n * Process-wide stdout scheduler for multi-session RPC mode.\n *\n * Each queue contains complete structured JSONL records for one routing handle.\n * Draining takes one record per queue in round-robin order and waits for stdout\n * backpressure before selecting the next one. A record is deliberately written\n * by itself: coalescing records from different sessions would obscure the\n * scheduling boundary and violate D9.\n */\nexport class SessionEventWriter {\n\tprivate readonly queues = new Map<string, RecordQueue>();\n\tprivate readonly fanout = new SessionEventFanout();\n\tprivate readonly connectionContext = new AsyncLocalStorage<string>();\n\tprivate readonly controlQueue: RecordQueue = { latestByKey: new Map(), ready: false };\n\tprivate readonly readyQueues: RecordQueue[] = [];\n\tprivate readonly sealedSessions = new Set<string>();\n\tprivate readonly writeRaw: RawWriter;\n\tprivate readonly waitForBackpressure?: BackpressureWaiter;\n\tprivate readonly scheduleFlush: FlushScheduler;\n\tprivate flushScheduled = false;\n\tprivate drainPromise?: Promise<void>;\n\tprivate inFlight?: { queue: RecordQueue; node: QueueNode };\n\tprivate failure?: unknown;\n\n\tconstructor(writeRaw: RawWriter, scheduleFlush?: FlushScheduler);\n\tconstructor(writeRaw: RawWriter, waitForBackpressure: BackpressureWaiter, scheduleFlush?: FlushScheduler);\n\tconstructor(\n\t\twriteRaw: RawWriter,\n\t\twaitOrSchedule?: BackpressureWaiter | FlushScheduler,\n\t\tscheduleFlush?: FlushScheduler,\n\t) {\n\t\tthis.writeRaw = writeRaw;\n\t\tif (waitOrSchedule && scheduleFlush === undefined && waitOrSchedule.length > 0) {\n\t\t\tthis.scheduleFlush = waitOrSchedule as FlushScheduler;\n\t\t} else {\n\t\t\tthis.waitForBackpressure = waitOrSchedule as BackpressureWaiter | undefined;\n\t\t\tthis.scheduleFlush = scheduleFlush ?? ((flush) => queueMicrotask(() => void flush()));\n\t\t}\n\t}\n\n\tget bufferedRecordCount(): number {\n\t\tlet count = this.inFlight ? 1 : 0;\n\t\tfor (const queue of this.allQueues()) {\n\t\t\tfor (let node = queue.head; node; node = node.next) count++;\n\t\t}\n\t\treturn count;\n\t}\n\n\tget bufferedByteLength(): number {\n\t\tlet bytes = this.inFlight ? Buffer.byteLength(serializeJsonLine(this.inFlight.node.value)) : 0;\n\t\tfor (const queue of this.allQueues()) {\n\t\t\tfor (let node = queue.head; node; node = node.next) {\n\t\t\t\tbytes += Buffer.byteLength(serializeJsonLine(node.value));\n\t\t\t}\n\t\t}\n\t\treturn bytes;\n\t}\n\n\tregisterConnection(id: string, connection: SessionEventWriterConnection): void {\n\t\tthis.fanout.registerConnection(id, connection);\n\t}\n\n\tunregisterConnection(id: string): void {\n\t\tthis.fanout.unregisterConnection(id);\n\t}\n\n\tattachConnectionToSession(id: string, sessionId: string): void {\n\t\tthis.fanout.attachConnectionToSession(id, sessionId);\n\t}\n\n\tdetachConnectionFromSession(id: string, sessionId: string): void {\n\t\tthis.fanout.detachConnectionFromSession(id, sessionId);\n\t}\n\n\tsetConnectionCapabilities(id: string, capabilities: readonly string[]): void {\n\t\tthis.fanout.setConnectionCapabilities(id, capabilities);\n\t}\n\n\tclearConnectionCapabilities(id: string): void {\n\t\tthis.fanout.clearConnectionCapabilities(id);\n\t}\n\n\thasRegisteredConnectionCapabilities(id: string): boolean {\n\t\treturn this.fanout.hasRegisteredConnectionCapabilities(id);\n\t}\n\n\tgetConnectionCapabilities(id: string): readonly string[] | undefined {\n\t\treturn this.fanout.getConnectionCapabilities(id);\n\t}\n\n\thasCapableConnection(sessionId: string): boolean {\n\t\treturn this.fanout.hasCapableConnection(sessionId);\n\t}\n\n\t/** Execute a connection's command with its response destination in context. */\n\twithConnection<T>(id: string, task: () => T): T {\n\t\treturn this.connectionContext.run(id, task);\n\t}\n\n\t/** Connection id of the command currently being dispatched, when one owns it. */\n\tcurrentConnection(): string | undefined {\n\t\treturn this.connectionContext.getStore();\n\t}\n\n\t/** Queue a session record. Content events target connections attached to the session. */\n\tenqueue(sessionId: string, value: object): boolean {\n\t\tif (this.sealedSessions.has(sessionId)) return false;\n\t\tconst targetId = this.connectionContext.getStore();\n\t\tconst record = value as RpcRecord;\n\t\tconst isTargeted =\n\t\t\trecord.type === \"response\" ||\n\t\t\trecord.type === \"bash_execution_update\" ||\n\t\t\t(record.type === \"extension_ui_request\" &&\n\t\t\t\t[\"select\", \"confirm\", \"input\", \"editor\"].includes(String(record.method)));\n\t\tconst tagged = { ...value, sessionId } as RpcRecord;\n\t\tconst { [RENDERED_COMPONENT_RECORD]: _rendered, ...wireTagged } = tagged;\n\t\tconst line = serializeJsonLine(wireTagged);\n\t\tif (!isTargeted) this.fanout.rememberSnapshot(sessionId, tagged, line);\n\t\tconst targets = this.fanout.targets(sessionId, targetId, isTargeted, record[RENDERED_COMPONENT_RECORD] === true);\n\t\tfor (const target of targets) {\n\t\t\tif (target !== undefined && !this.fanout.get(target)) continue;\n\t\t\tconst registered = target === undefined ? undefined : this.fanout.get(target);\n\t\t\tif (registered)\n\t\t\t\tregistered.actor.enqueue(line, compactDelta(tagged) && tagged.message !== null ? MESSAGE_KEY : undefined);\n\t\t\telse this.appendSessionRecord(sessionId, wireTagged, target);\n\t\t}\n\t\tthis.requestFlush();\n\t\treturn true;\n\t}\n\n\t/** Queue one untagged host-control response for the current connection. */\n\tenqueueControl(value: object): Promise<void> {\n\t\tif (this.failure !== undefined) return Promise.reject(this.failure);\n\t\tconst targetId = this.connectionContext.getStore();\n\t\tconst registered = targetId === undefined ? undefined : this.fanout.get(targetId);\n\t\tif (registered) {\n\t\t\tregistered.actor.enqueue(serializeJsonLine(value));\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tconst queue = targetId === undefined ? this.controlQueue : this.connectionQueue(targetId);\n\t\tconst completion = new Promise<void>((resolve, reject) => {\n\t\t\tthis.append(queue, { ...value }, undefined, resolve, reject);\n\t\t});\n\t\tthis.markReady(queue);\n\t\tthis.requestFlush();\n\t\treturn completion;\n\t}\n\n\t/**\n\t * Prevent subsequent records for a session and append its terminal response.\n\t * Existing records retain FIFO order; this response is therefore that\n\t * session's final stdout record.\n\t */\n\tcloseSession(sessionId: string, response: object): void {\n\t\tif (this.sealedSessions.has(sessionId)) return;\n\t\tthis.sealedSessions.add(sessionId);\n\t\tconst targetId = this.connectionContext.getStore();\n\t\tconst lifecycle = { type: \"session_closed\", sessionId };\n\t\tthis.fanout.broadcast(serializeJsonLine(lifecycle));\n\t\tconst taggedResponse = { ...response, sessionId };\n\t\tconst registered = targetId === undefined ? undefined : this.fanout.get(targetId);\n\t\tif (registered) registered.actor.enqueue(serializeJsonLine(taggedResponse));\n\t\telse this.appendSessionRecord(sessionId, taggedResponse, targetId);\n\t\tthis.requestFlush();\n\t}\n\n\t/**\n\t * Drops per-session bookkeeping for a handle whose runtime is fully disposed.\n\t * Routing handles are unique per process epoch, so nothing can legitimately\n\t * emit under this id again; without this every host-closed session would\n\t * leave a permanent sealed-handle (and snapshot) entry behind.\n\t */\n\tforgetSession(sessionId: string): void {\n\t\tthis.sealedSessions.delete(sessionId);\n\t\tthis.fanout.forgetSession(sessionId);\n\t}\n\n\t/** Drain every retained lane and the current in-flight record. */\n\tflush(): Promise<void> {\n\t\tif (this.failure !== undefined) return Promise.reject(this.failure);\n\t\tthis.flushScheduled = false;\n\t\tif (this.drainPromise) return this.drainPromise;\n\t\tif (this.readyQueues.length === 0)\n\t\t\treturn Promise.all([...this.fanout.values()].map(({ actor }) => actor.flush())).then(() => undefined);\n\t\tlet resolveDrain!: () => void;\n\t\tlet rejectDrain!: (cause: unknown) => void;\n\t\tconst drain = new Promise<void>((resolve, reject) => {\n\t\t\tresolveDrain = resolve;\n\t\t\trejectDrain = reject;\n\t\t});\n\t\tthis.drainPromise = drain;\n\t\tvoid this.drainUntilEmpty().then(resolveDrain, rejectDrain);\n\t\tvoid drain.then(\n\t\t\t() => {\n\t\t\t\tif (this.drainPromise === drain) this.drainPromise = undefined;\n\t\t\t\tif (this.readyQueues.length > 0) this.requestFlush();\n\t\t\t},\n\t\t\t(cause) => {\n\t\t\t\tif (this.drainPromise === drain) this.drainPromise = undefined;\n\t\t\t\tthis.fail(cause);\n\t\t\t},\n\t\t);\n\t\treturn drain;\n\t}\n\n\tprivate async drainUntilEmpty(): Promise<void> {\n\t\tdo {\n\t\t\tawait this.drainReadyQueues();\n\t\t} while (this.readyQueues.length > 0);\n\t\tawait Promise.all([...this.fanout.values()].map(({ actor }) => actor.flush()));\n\t}\n\n\tprivate async drainReadyQueues(): Promise<void> {\n\t\twhile (this.readyQueues.length > 0) {\n\t\t\tconst queue = this.readyQueues.shift()!;\n\t\t\tqueue.ready = false;\n\t\t\tconst node = queue.head;\n\t\t\tif (!node) continue;\n\n\t\t\tthis.unlink(queue, node);\n\t\t\tthis.inFlight = { queue, node };\n\t\t\ttry {\n\t\t\t\t// D9: exactly one complete record per raw write. The next lane is not\n\t\t\t\t// selected until this record has cleared stdout backpressure.\n\t\t\t\tconst connection = queue.targetId ? this.fanout.get(queue.targetId)?.connection : undefined;\n\t\t\t\tconst writeRaw = connection?.writeRaw ?? this.writeRaw;\n\t\t\t\tconst waitForBackpressure = connection?.waitForBackpressure ?? this.waitForBackpressure;\n\t\t\t\tif (!connection && queue.targetId) {\n\t\t\t\t\tnode.resolve?.();\n\t\t\t\t} else {\n\t\t\t\t\twriteRaw(serializeJsonLine(node.value));\n\t\t\t\t\tif (waitForBackpressure) await waitForBackpressure();\n\t\t\t\t\tnode.resolve?.();\n\t\t\t\t}\n\t\t\t} catch (cause) {\n\t\t\t\tnode.reject?.(cause);\n\t\t\t\tthrow cause;\n\t\t\t} finally {\n\t\t\t\tthis.inFlight = undefined;\n\t\t\t}\n\n\t\t\tif (queue.head) {\n\t\t\t\tthis.markReady(queue);\n\t\t\t} else if (queue.sessionId || queue.targetId) {\n\t\t\t\tfor (const [key, candidate] of this.queues) {\n\t\t\t\t\tif (candidate === queue) this.queues.delete(key);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate connectionQueue(targetId: string): RecordQueue {\n\t\tconst key = `connection:${targetId}`;\n\t\tlet queue = this.queues.get(key);\n\t\tif (!queue) {\n\t\t\tqueue = { targetId, latestByKey: new Map(), ready: false };\n\t\t\tthis.queues.set(key, queue);\n\t\t}\n\t\treturn queue;\n\t}\n\n\tprivate appendSessionRecord(sessionId: string, value: RpcRecord, targetId?: string): void {\n\t\tconst key = `${targetId ?? \"default\"}:${sessionId}`;\n\t\tlet queue = this.queues.get(key);\n\t\tif (!queue) {\n\t\t\tqueue = { sessionId, targetId, latestByKey: new Map(), ready: false };\n\t\t\tthis.queues.set(key, queue);\n\t\t}\n\n\t\tconst delta = compactDelta(value);\n\t\tif (delta) {\n\t\t\tconst previousFull = queue.latestByKey.get(MESSAGE_KEY);\n\t\t\tif (previousFull) this.demoteAndMerge(queue, previousFull);\n\t\t\tconst node = this.append(queue, value, MESSAGE_KEY);\n\t\t\tqueue.latestByKey.set(MESSAGE_KEY, node);\n\t\t\tthis.markReady(queue);\n\t\t\treturn;\n\t\t}\n\n\t\tconst toolKey = toolUpdateKey(value);\n\t\tif (toolKey) {\n\t\t\tconst previous = queue.latestByKey.get(toolKey);\n\t\t\tif (previous) this.unlink(queue, previous);\n\t\t\tconst node = this.append(queue, value, toolKey);\n\t\t\tqueue.latestByKey.set(toolKey, node);\n\t\t\tthis.markReady(queue);\n\t\t\treturn;\n\t\t}\n\n\t\t// All non-compactable records are ordering barriers. In particular this\n\t\t// includes delta-only/full non-delta message updates, protocol responses,\n\t\t// extension UI requests, errors, retries, lifecycle, and unknown records.\n\t\tqueue.latestByKey.clear();\n\t\tthis.append(queue, value);\n\t\tthis.markReady(queue);\n\t}\n\n\tprivate demoteAndMerge(queue: RecordQueue, node: QueueNode): void {\n\t\tconst event = node.value.assistantMessageEvent as Record<string, unknown>;\n\t\tnode.value = {\n\t\t\t...node.value,\n\t\t\tmessage: null,\n\t\t\tassistantMessageEvent: { ...event, partial: null },\n\t\t};\n\t\tconst current = compactDelta(node.value);\n\t\tconst preceding = node.previous;\n\t\tconst previous = preceding ? compactDelta(preceding.value) : undefined;\n\t\tif (\n\t\t\tpreceding &&\n\t\t\tprevious &&\n\t\t\tcurrent &&\n\t\t\tpreceding.value.message === null &&\n\t\t\tprevious.type === current.type &&\n\t\t\tprevious.contentIndex === current.contentIndex\n\t\t) {\n\t\t\tconst precedingEvent = preceding.value.assistantMessageEvent as Record<string, unknown>;\n\t\t\tpreceding.value = {\n\t\t\t\t...preceding.value,\n\t\t\t\tassistantMessageEvent: { ...precedingEvent, delta: previous.delta + current.delta },\n\t\t\t};\n\t\t\tthis.unlink(queue, node);\n\t\t}\n\t}\n\n\tprivate append(\n\t\tqueue: RecordQueue,\n\t\tvalue: RpcRecord,\n\t\tkey?: string,\n\t\tresolve?: () => void,\n\t\treject?: (cause: unknown) => void,\n\t): QueueNode {\n\t\tconst node: QueueNode = { value, key, previous: queue.tail, resolve, reject };\n\t\tif (queue.tail) queue.tail.next = node;\n\t\telse queue.head = node;\n\t\tqueue.tail = node;\n\t\treturn node;\n\t}\n\n\tprivate unlink(queue: RecordQueue, node: QueueNode): void {\n\t\tif (node.previous) node.previous.next = node.next;\n\t\telse queue.head = node.next;\n\t\tif (node.next) node.next.previous = node.previous;\n\t\telse queue.tail = node.previous;\n\t\tif (node.key && queue.latestByKey.get(node.key) === node) queue.latestByKey.delete(node.key);\n\t\tnode.previous = undefined;\n\t\tnode.next = undefined;\n\t}\n\n\tprivate markReady(queue: RecordQueue): void {\n\t\tif (queue.ready || this.inFlight?.queue === queue || !queue.head) return;\n\t\tqueue.ready = true;\n\t\tthis.readyQueues.push(queue);\n\t}\n\n\tprivate requestFlush(): void {\n\t\tif (this.failure !== undefined || this.flushScheduled || this.drainPromise) return;\n\t\tthis.flushScheduled = true;\n\t\tthis.scheduleFlush(() => this.flush());\n\t}\n\n\tprivate fail(cause: unknown): void {\n\t\tif (this.failure !== undefined) return;\n\t\tthis.failure = cause;\n\t\tfor (const queue of this.allQueues()) {\n\t\t\tfor (let node = queue.head; node; node = node.next) node.reject?.(cause);\n\t\t}\n\t}\n\n\tprivate *allQueues(): Iterable<RecordQueue> {\n\t\tyield* this.queues.values();\n\t\tyield this.controlQueue;\n\t}\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Socket } from "node:net";
|
|
2
|
+
export declare const SOCKET_SECRET_BYTES = 32;
|
|
3
|
+
export declare const SOCKET_SECRET_SUFFIX = ".secret";
|
|
4
|
+
export declare const SOCKET_SECRET_FILE_ENV = "SENPI_RPC_SOCKET_SECRET_FILE";
|
|
5
|
+
export declare const SOCKET_HANDSHAKE_TIMEOUT_MS = 2000;
|
|
6
|
+
export declare function socketSecretPath(logicalPath: string): string;
|
|
7
|
+
export declare function ensureSocketSecret(path: string): Promise<Buffer>;
|
|
8
|
+
export declare function createSocketSecret(path: string): Promise<Buffer>;
|
|
9
|
+
export declare function readSocketSecret(path: string): Promise<Buffer>;
|
|
10
|
+
export declare function resolveSocketTransportAddress(socketPath: string, platform: NodeJS.Platform, secret?: Uint8Array): string;
|
|
11
|
+
export declare function authenticateSocket(socket: Socket, secret: Uint8Array, onAuthenticated: () => void): void;
|
|
12
|
+
export declare function sendSocketHandshake(socket: Socket, secret: Uint8Array): void;
|
|
13
|
+
//# sourceMappingURL=socket-transport.d.ts.map
|