agentcut 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +11 -2
- package/dist/bridge.d.ts +45 -0
- package/dist/bridge.js +691 -0
- package/dist/bridge.js.map +1 -0
- package/dist/config.d.ts +13 -0
- package/dist/config.js +50 -0
- package/dist/config.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +35 -0
- package/dist/index.js.map +1 -0
- package/dist/log.d.ts +1 -0
- package/dist/log.js +14 -0
- package/dist/log.js.map +1 -0
- package/dist/studio/agents/claude.d.ts +7 -0
- package/dist/studio/agents/claude.js +155 -0
- package/dist/studio/agents/claude.js.map +1 -0
- package/dist/studio/agents/codex.d.ts +4 -0
- package/dist/studio/agents/codex.js +169 -0
- package/dist/studio/agents/codex.js.map +1 -0
- package/dist/studio/agents/index.d.ts +8 -0
- package/dist/studio/agents/index.js +50 -0
- package/dist/studio/agents/index.js.map +1 -0
- package/dist/studio/agents/types.d.ts +131 -0
- package/dist/studio/agents/types.js +11 -0
- package/dist/studio/agents/types.js.map +1 -0
- package/dist/studio/bundler.d.ts +29 -0
- package/dist/studio/bundler.js +136 -0
- package/dist/studio/bundler.js.map +1 -0
- package/dist/studio/chat.d.ts +147 -0
- package/dist/studio/chat.js +681 -0
- package/dist/studio/chat.js.map +1 -0
- package/dist/studio/cli.d.ts +2 -0
- package/dist/studio/cli.js +194 -0
- package/dist/studio/cli.js.map +1 -0
- package/dist/studio/components.d.ts +4 -0
- package/dist/studio/components.js +36 -0
- package/dist/studio/components.js.map +1 -0
- package/dist/studio/host.d.ts +105 -0
- package/dist/studio/host.js +634 -0
- package/dist/studio/host.js.map +1 -0
- package/dist/studio/http.d.ts +21 -0
- package/dist/studio/http.js +240 -0
- package/dist/studio/http.js.map +1 -0
- package/dist/studio/music.d.ts +35 -0
- package/dist/studio/music.js +130 -0
- package/dist/studio/music.js.map +1 -0
- package/dist/studio/proc.d.ts +11 -0
- package/dist/studio/proc.js +69 -0
- package/dist/studio/proc.js.map +1 -0
- package/dist/studio/projects.d.ts +84 -0
- package/dist/studio/projects.js +369 -0
- package/dist/studio/projects.js.map +1 -0
- package/dist/studio/render.d.ts +24 -0
- package/dist/studio/render.js +197 -0
- package/dist/studio/render.js.map +1 -0
- package/dist/studio/reveal.d.ts +7 -0
- package/dist/studio/reveal.js +49 -0
- package/dist/studio/reveal.js.map +1 -0
- package/dist/studio/schema.d.ts +4152 -0
- package/dist/studio/schema.js +358 -0
- package/dist/studio/schema.js.map +1 -0
- package/dist/studio/tools.d.ts +2 -0
- package/dist/studio/tools.js +165 -0
- package/dist/studio/tools.js.map +1 -0
- package/dist/studio/voice.d.ts +150 -0
- package/dist/studio/voice.js +434 -0
- package/dist/studio/voice.js.map +1 -0
- package/dist/studio/workspace.d.ts +31 -0
- package/dist/studio/workspace.js +187 -0
- package/dist/studio/workspace.js.map +1 -0
- package/package.json +50 -4
- package/template/AGENTS.md +13 -0
- package/template/components/CATALOG.md +1306 -0
- package/template/components/README.md +61 -0
- package/template/components/STYLES.md +246 -0
- package/template/components/arcade-title/ArcadeTitle.tsx +860 -0
- package/template/components/arcade-title/meta.json +28 -0
- package/template/components/aurora/Aurora.tsx +63 -0
- package/template/components/aurora/meta.json +28 -0
- package/template/components/bar-wipe-title/BarWipeTitle.tsx +94 -0
- package/template/components/bar-wipe-title/meta.json +29 -0
- package/template/components/before-after/BeforeAfter.tsx +89 -0
- package/template/components/before-after/meta.json +233 -0
- package/template/components/bento-grid/BentoGrid.tsx +202 -0
- package/template/components/bento-grid/meta.json +25 -0
- package/template/components/blur-in-title/BlurInTitle.tsx +121 -0
- package/template/components/blur-in-title/meta.json +32 -0
- package/template/components/catalog.json +8730 -0
- package/template/components/catalog.ts +103 -0
- package/template/components/chat-thread/ChatThread.tsx +128 -0
- package/template/components/chat-thread/meta.json +24 -0
- package/template/components/checklist/Checklist.tsx +129 -0
- package/template/components/checklist/meta.json +25 -0
- package/template/components/confetti/Confetti.tsx +109 -0
- package/template/components/confetti/meta.json +28 -0
- package/template/components/countdown/Countdown.tsx +166 -0
- package/template/components/countdown/meta.json +28 -0
- package/template/components/cut-and-paste/CutAndPaste.tsx +654 -0
- package/template/components/cut-and-paste/meta.json +29 -0
- package/template/components/decode-text/DecodeText.tsx +97 -0
- package/template/components/decode-text/meta.json +29 -0
- package/template/components/editorial-quote/EditorialQuote.tsx +122 -0
- package/template/components/editorial-quote/meta.json +28 -0
- package/template/components/glitch-title/GlitchTitle.tsx +171 -0
- package/template/components/glitch-title/meta.json +32 -0
- package/template/components/halftone-wave/HalftoneWave.tsx +106 -0
- package/template/components/halftone-wave/meta.json +28 -0
- package/template/components/highlighter/Highlighter.tsx +142 -0
- package/template/components/highlighter/meta.json +28 -0
- package/template/components/hook-card/HookCard.tsx +552 -0
- package/template/components/hook-card/meta.json +304 -0
- package/template/components/index.ts +149 -0
- package/template/components/iris-wipe/IrisWipe.tsx +76 -0
- package/template/components/iris-wipe/meta.json +24 -0
- package/template/components/kinetic-poster/KineticPoster.tsx +437 -0
- package/template/components/kinetic-poster/meta.json +31 -0
- package/template/components/kinetic-punch/KineticPunch.tsx +80 -0
- package/template/components/kinetic-punch/meta.json +30 -0
- package/template/components/lava-lamp/LavaLamp.tsx +92 -0
- package/template/components/lava-lamp/meta.json +28 -0
- package/template/components/letter-cascade/LetterCascade.tsx +102 -0
- package/template/components/letter-cascade/meta.json +29 -0
- package/template/components/lib.ts +179 -0
- package/template/components/light-leak/LightLeakTransition.tsx +43 -0
- package/template/components/light-leak/meta.json +74 -0
- package/template/components/line-diagram/LineDiagram.tsx +205 -0
- package/template/components/line-diagram/meta.json +217 -0
- package/template/components/list-card/ListCard.tsx +104 -0
- package/template/components/list-card/meta.json +232 -0
- package/template/components/logo-sting/LogoSting.tsx +129 -0
- package/template/components/logo-sting/meta.json +29 -0
- package/template/components/looks.tsx +1447 -0
- package/template/components/lower-third/LowerThird.tsx +100 -0
- package/template/components/lower-third/meta.json +24 -0
- package/template/components/marquee/Marquee.tsx +100 -0
- package/template/components/marquee/meta.json +30 -0
- package/template/components/notification/Notification.tsx +115 -0
- package/template/components/notification/meta.json +27 -0
- package/template/components/outline-fill/OutlineFill.tsx +106 -0
- package/template/components/outline-fill/meta.json +28 -0
- package/template/components/panel-sweep/PanelSweep.tsx +86 -0
- package/template/components/panel-sweep/meta.json +25 -0
- package/template/components/prompt-box/PromptBox.tsx +131 -0
- package/template/components/prompt-box/meta.json +24 -0
- package/template/components/props.ts +73 -0
- package/template/components/quote-card/QuoteCard.tsx +71 -0
- package/template/components/quote-card/meta.json +216 -0
- package/template/components/shape-shift/ShapeShift.tsx +420 -0
- package/template/components/shape-shift/meta.json +31 -0
- package/template/components/slide-zoom-message/SlideZoomMessage.tsx +179 -0
- package/template/components/slide-zoom-message/meta.json +199 -0
- package/template/components/social-post/SocialPost.tsx +185 -0
- package/template/components/social-post/meta.json +30 -0
- package/template/components/split-flap/SplitFlap.tsx +191 -0
- package/template/components/split-flap/meta.json +29 -0
- package/template/components/spotlight-grid/SpotlightGrid.tsx +84 -0
- package/template/components/spotlight-grid/meta.json +25 -0
- package/template/components/stat-counter/StatCounter.tsx +117 -0
- package/template/components/stat-counter/meta.json +27 -0
- package/template/components/sticker-badge/StickerBadge.tsx +46 -0
- package/template/components/sticker-badge/meta.json +220 -0
- package/template/components/sticker-slam/StickerSlam.tsx +941 -0
- package/template/components/sticker-slam/meta.json +34 -0
- package/template/components/style-layer.tsx +233 -0
- package/template/components/styles.json +762 -0
- package/template/components/styles.ts +113 -0
- package/template/components/target-lock/TargetLock.tsx +662 -0
- package/template/components/target-lock/meta.json +32 -0
- package/template/components/text-reveal/TextReveal.tsx +99 -0
- package/template/components/text-reveal/meta.json +28 -0
- package/template/components/tile-wipe/TileWipe.tsx +75 -0
- package/template/components/tile-wipe/meta.json +24 -0
- package/template/components/type-zoom/TypeZoom.tsx +103 -0
- package/template/components/type-zoom/meta.json +27 -0
- package/template/components/types.ts +66 -0
- package/template/components/typewriter/Typewriter.tsx +112 -0
- package/template/components/typewriter/meta.json +29 -0
- package/template/components/word-pop/WordPop.tsx +59 -0
- package/template/components/word-pop/meta.json +237 -0
- package/template/components/word-stack/WordStack.tsx +122 -0
- package/template/components/word-stack/meta.json +27 -0
- package/template/components/word-swap/WordSwap.tsx +127 -0
- package/template/components/word-swap/meta.json +30 -0
- package/template/presets/charcoal-sketch/PROMPT.md +48 -0
- package/template/presets/charcoal-sketch/assets/paper/grain-0.png +0 -0
- package/template/presets/charcoal-sketch/assets/paper/grain-1.png +0 -0
- package/template/presets/charcoal-sketch/assets/paper/grain-2.png +0 -0
- package/template/presets/charcoal-sketch/assets/paper/sketch-paper.jpg +0 -0
- package/template/presets/charcoal-sketch/assets/paper/smudge.png +0 -0
- package/template/presets/charcoal-sketch/poster.jpg +0 -0
- package/template/presets/charcoal-sketch/preset.json +17 -0
- package/template/presets/charcoal-sketch/preview.mp4 +0 -0
- package/template/presets/charcoal-sketch/scenes/Grain.tsx +23 -0
- package/template/presets/charcoal-sketch/scenes/Paper.tsx +17 -0
- package/template/presets/charcoal-sketch/scenes/examples/Agents.tsx +100 -0
- package/template/presets/charcoal-sketch/scenes/examples/Approvals.tsx +110 -0
- package/template/presets/charcoal-sketch/scenes/examples/Blog.tsx +105 -0
- package/template/presets/charcoal-sketch/scenes/examples/EndCard.tsx +41 -0
- package/template/presets/charcoal-sketch/scenes/examples/Hook.tsx +130 -0
- package/template/presets/charcoal-sketch/scenes/examples/Ideas.tsx +92 -0
- package/template/presets/charcoal-sketch/scenes/examples/Posting.tsx +128 -0
- package/template/presets/charcoal-sketch/scenes/lib/painfix.tsx +119 -0
- package/template/presets/charcoal-sketch/scenes/lib/sketch.tsx +291 -0
- package/template/presets/charcoal-sketch/scripts/build_layers.example.py +193 -0
- package/template/presets/charcoal-sketch/scripts/duck_music.py +34 -0
- package/template/presets/charcoal-sketch/scripts/make_textures.py +93 -0
- package/template/presets/punk-cut-paper/PROMPT.md +37 -0
- package/template/presets/punk-cut-paper/assets/paper/desk-cream.jpg +0 -0
- package/template/presets/punk-cut-paper/assets/paper/grain-overlay.png +0 -0
- package/template/presets/punk-cut-paper/assets/paper/halftone-black.png +0 -0
- package/template/presets/punk-cut-paper/assets/paper/halftone-red.png +0 -0
- package/template/presets/punk-cut-paper/assets/paper/halftone-yellow.png +0 -0
- package/template/presets/punk-cut-paper/assets/paper/kraft.jpg +0 -0
- package/template/presets/punk-cut-paper/assets/paper/newsprint.jpg +0 -0
- package/template/presets/punk-cut-paper/assets/paper/paper-cream.jpg +0 -0
- package/template/presets/punk-cut-paper/assets/paper/paper-white.jpg +0 -0
- package/template/presets/punk-cut-paper/assets/paper/tape.png +0 -0
- package/template/presets/punk-cut-paper/build_layers.example.py +150 -0
- package/template/presets/punk-cut-paper/poster.jpg +0 -0
- package/template/presets/punk-cut-paper/preset.json +15 -0
- package/template/presets/punk-cut-paper/preview.mp4 +0 -0
- package/template/presets/punk-cut-paper/scenes/Backdrop.tsx +76 -0
- package/template/presets/punk-cut-paper/scenes/Motif.tsx +376 -0
- package/template/presets/punk-cut-paper/scenes/Photo.tsx +73 -0
- package/template/presets/punk-cut-paper/scenes/Ransom.tsx +119 -0
- package/template/presets/punk-cut-paper/scenes/Xerox.tsx +31 -0
- package/template/presets/punk-cut-paper/scenes/lib/punk.tsx +208 -0
- package/template/runtime/composition.tsx +918 -0
- package/template/runtime/helpers.tsx +228 -0
- package/template/runtime/index.tsx +22 -0
- package/template/runtime/types.ts +248 -0
- package/template/skill/SKILL.md +149 -0
- package/template/skill/references/browser-export.md +61 -0
- package/template/skill/references/components.md +38 -0
- package/template/skill/references/craft.md +53 -0
- package/template/skill/references/cursor.md +91 -0
- package/template/skill/references/footage.md +73 -0
- package/template/skill/references/format.md +140 -0
- package/template/skill/references/presets.md +56 -0
- package/template/skill/references/sound.md +128 -0
- package/template/starter/.studio/chat.json +1 -0
- package/template/starter/assets/.keep +0 -0
- package/template/starter/layers.json +46 -0
- package/template/starter/notes.md +4 -0
- package/template/starter/project.json +13 -0
- package/template/starter/renders/.keep +0 -0
- package/template/starter/scenes/Title.tsx +38 -0
package/dist/bridge.js
ADDED
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdirSync, readdirSync, rmSync, statSync, writeFileSync, } from "node:fs";
|
|
3
|
+
import { createServer, request as httpRequest } from "node:http";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { AGENT_FRAMES_DIR, getConfig, PACKAGE_VERSION, WS_PATH } from "./config.js";
|
|
7
|
+
import { debugLog } from "./log.js";
|
|
8
|
+
// Editor calls (export, capture, generation) can run long; keep the WS and HTTP
|
|
9
|
+
// fallback paths on the same ceiling. The status probe is a quick liveness check.
|
|
10
|
+
const EDITOR_CALL_TIMEOUT_MS = 120_000;
|
|
11
|
+
const BRIDGE_PROBE_TIMEOUT_MS = 5_000;
|
|
12
|
+
// Cap a single inbound WS message so a malformed/garbage length field (or a
|
|
13
|
+
// runaway editor) cannot make us allocate unbounded memory. Real payloads
|
|
14
|
+
// (exported MP4, captured PNGs as data URLs) are large but well under this.
|
|
15
|
+
const MAX_WS_MESSAGE_BYTES = 256 * 1024 * 1024;
|
|
16
|
+
// Persisted frames are best-effort scratch data. Keep the directory bounded so
|
|
17
|
+
// long-lived sessions don't accumulate forever.
|
|
18
|
+
const MAX_AGENT_FRAMES = 200;
|
|
19
|
+
const MAX_AGENT_FRAME_AGE_MS = 6 * 60 * 60 * 1000;
|
|
20
|
+
let resolvedFramesDir = null;
|
|
21
|
+
let framesWrittenSincePrune = 0;
|
|
22
|
+
function resolveFramesDir() {
|
|
23
|
+
if (resolvedFramesDir)
|
|
24
|
+
return resolvedFramesDir;
|
|
25
|
+
const candidates = [
|
|
26
|
+
AGENT_FRAMES_DIR,
|
|
27
|
+
join(tmpdir(), "agentcut-frames"),
|
|
28
|
+
];
|
|
29
|
+
for (const candidate of candidates) {
|
|
30
|
+
try {
|
|
31
|
+
mkdirSync(candidate, { recursive: true });
|
|
32
|
+
resolvedFramesDir = candidate;
|
|
33
|
+
return candidate;
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
debugLog(`agent frames dir unavailable ${candidate}: ${error instanceof Error ? error.message : String(error)}`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// Last resort: the tmp root always exists.
|
|
40
|
+
resolvedFramesDir = tmpdir();
|
|
41
|
+
return resolvedFramesDir;
|
|
42
|
+
}
|
|
43
|
+
function pruneAgentFrames(directory) {
|
|
44
|
+
try {
|
|
45
|
+
const entries = readdirSync(directory)
|
|
46
|
+
.filter((name) => name.startsWith("agentcut-frame-"))
|
|
47
|
+
.map((name) => {
|
|
48
|
+
const full = join(directory, name);
|
|
49
|
+
try {
|
|
50
|
+
return { full, mtime: statSync(full).mtimeMs };
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
})
|
|
56
|
+
.filter((entry) => entry !== null);
|
|
57
|
+
const now = Date.now();
|
|
58
|
+
const survivors = [];
|
|
59
|
+
for (const entry of entries) {
|
|
60
|
+
if (now - entry.mtime > MAX_AGENT_FRAME_AGE_MS) {
|
|
61
|
+
try {
|
|
62
|
+
rmSync(entry.full, { force: true });
|
|
63
|
+
}
|
|
64
|
+
catch { }
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
survivors.push(entry);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (survivors.length > MAX_AGENT_FRAMES) {
|
|
71
|
+
survivors.sort((a, b) => a.mtime - b.mtime);
|
|
72
|
+
const excess = survivors.slice(0, survivors.length - MAX_AGENT_FRAMES);
|
|
73
|
+
for (const entry of excess) {
|
|
74
|
+
try {
|
|
75
|
+
rmSync(entry.full, { force: true });
|
|
76
|
+
}
|
|
77
|
+
catch { }
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
debugLog(`agent frame prune failed ${error instanceof Error ? error.message : String(error)}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
let extension = null;
|
|
86
|
+
export function setBridgeExtension(next) {
|
|
87
|
+
extension = next;
|
|
88
|
+
}
|
|
89
|
+
/** Push a message to the connected page (no-op when none). */
|
|
90
|
+
export function sendToEditor(payload) {
|
|
91
|
+
if (activeEditor && !activeEditor.closed)
|
|
92
|
+
activeEditor.sendJson(payload);
|
|
93
|
+
}
|
|
94
|
+
export function getEditorSession() {
|
|
95
|
+
return activeEditor && !activeEditor.closed ? editorSession : null;
|
|
96
|
+
}
|
|
97
|
+
let serverPromise = null;
|
|
98
|
+
let activeEditor = null;
|
|
99
|
+
let editorSession = null;
|
|
100
|
+
let editorRequestCounter = 0;
|
|
101
|
+
const pendingEditorRequests = new Map();
|
|
102
|
+
function isLocalRequest(request) {
|
|
103
|
+
const address = request.socket.remoteAddress;
|
|
104
|
+
const { host, port } = getConfig();
|
|
105
|
+
const authority = request.headers.host?.toLowerCase();
|
|
106
|
+
if (authority !== `${host}:${port}` && authority !== `localhost:${port}`)
|
|
107
|
+
return false;
|
|
108
|
+
return (address === "127.0.0.1" ||
|
|
109
|
+
address === "::1" ||
|
|
110
|
+
address === "::ffff:127.0.0.1");
|
|
111
|
+
}
|
|
112
|
+
function headerValue(value) {
|
|
113
|
+
return Array.isArray(value) ? value[0] : value;
|
|
114
|
+
}
|
|
115
|
+
function createAcceptKey(key) {
|
|
116
|
+
return createHash("sha1")
|
|
117
|
+
.update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`)
|
|
118
|
+
.digest("base64");
|
|
119
|
+
}
|
|
120
|
+
function sendJsonResponse(response, status, body) {
|
|
121
|
+
const payload = JSON.stringify(body);
|
|
122
|
+
response.writeHead(status, {
|
|
123
|
+
"content-type": "application/json",
|
|
124
|
+
"content-length": Buffer.byteLength(payload),
|
|
125
|
+
});
|
|
126
|
+
response.end(payload);
|
|
127
|
+
}
|
|
128
|
+
async function readJsonBody(request) {
|
|
129
|
+
const chunks = [];
|
|
130
|
+
for await (const chunk of request) {
|
|
131
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
132
|
+
}
|
|
133
|
+
if (chunks.length === 0)
|
|
134
|
+
return {};
|
|
135
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
136
|
+
}
|
|
137
|
+
function persistSingleAgentFrameResult(result) {
|
|
138
|
+
if (!result || typeof result !== "object")
|
|
139
|
+
return result;
|
|
140
|
+
const frame = result;
|
|
141
|
+
const dataUrl = frame.dataUrl;
|
|
142
|
+
if (typeof dataUrl !== "string")
|
|
143
|
+
return result;
|
|
144
|
+
const match = /^data:([^;,]+);base64,([\s\S]+)$/.exec(dataUrl);
|
|
145
|
+
if (!match)
|
|
146
|
+
return result;
|
|
147
|
+
const mimeType = match[1] || String(frame.mimeType ?? "image/png");
|
|
148
|
+
const fileExtension = mimeType.includes("jpeg")
|
|
149
|
+
? "jpg"
|
|
150
|
+
: mimeType.includes("webp")
|
|
151
|
+
? "webp"
|
|
152
|
+
: "png";
|
|
153
|
+
const directory = resolveFramesDir();
|
|
154
|
+
const filename = `agentcut-frame-${Date.now()}-${randomUUID()}.${fileExtension}`;
|
|
155
|
+
const filePath = join(directory, filename);
|
|
156
|
+
const bytes = Buffer.from(match[2], "base64");
|
|
157
|
+
writeFileSync(filePath, bytes);
|
|
158
|
+
framesWrittenSincePrune += 1;
|
|
159
|
+
const rest = { ...frame };
|
|
160
|
+
delete rest.dataUrl;
|
|
161
|
+
return {
|
|
162
|
+
...rest,
|
|
163
|
+
mimeType,
|
|
164
|
+
size: bytes.length,
|
|
165
|
+
filePath,
|
|
166
|
+
filename,
|
|
167
|
+
dataUrlSaved: true,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
function persistAgentFrameResultInner(result, depth) {
|
|
171
|
+
// Bound recursion against a hostile/buggy editor response. Real frame
|
|
172
|
+
// payloads are shallow; nothing legitimate nests this deep.
|
|
173
|
+
if (depth > 64)
|
|
174
|
+
return result;
|
|
175
|
+
if (Array.isArray(result)) {
|
|
176
|
+
return result.map((item) => persistAgentFrameResultInner(item, depth + 1));
|
|
177
|
+
}
|
|
178
|
+
if (!result || typeof result !== "object")
|
|
179
|
+
return result;
|
|
180
|
+
const frame = result;
|
|
181
|
+
const persistedFrame = persistSingleAgentFrameResult(frame);
|
|
182
|
+
const output = {};
|
|
183
|
+
for (const [key, value] of Object.entries(persistedFrame)) {
|
|
184
|
+
output[key] = persistAgentFrameResultInner(value, depth + 1);
|
|
185
|
+
}
|
|
186
|
+
return output;
|
|
187
|
+
}
|
|
188
|
+
export function persistAgentFrameResult(result) {
|
|
189
|
+
const persisted = persistAgentFrameResultInner(result, 0);
|
|
190
|
+
// Prune only after a response that actually wrote frames, so frameless
|
|
191
|
+
// editor calls (get_project, etc.) don't trigger filesystem churn.
|
|
192
|
+
if (framesWrittenSincePrune > 0 && resolvedFramesDir) {
|
|
193
|
+
framesWrittenSincePrune = 0;
|
|
194
|
+
pruneAgentFrames(resolvedFramesDir);
|
|
195
|
+
}
|
|
196
|
+
return persisted;
|
|
197
|
+
}
|
|
198
|
+
class WebSocketConnection {
|
|
199
|
+
socket;
|
|
200
|
+
buffer = Buffer.alloc(0);
|
|
201
|
+
fragments = [];
|
|
202
|
+
fragmentOpcode = 0;
|
|
203
|
+
closed = false;
|
|
204
|
+
constructor(socket) {
|
|
205
|
+
this.socket = socket;
|
|
206
|
+
socket.on("data", (chunk) => this.read(chunk));
|
|
207
|
+
socket.on("close", () => this.close());
|
|
208
|
+
socket.on("error", (error) => {
|
|
209
|
+
debugLog(`editor socket error ${error.message}`);
|
|
210
|
+
this.close();
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
sendJson(value) {
|
|
214
|
+
this.sendText(JSON.stringify(value));
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Close the page connection. With a code the page gets a proper close frame, so it can tell
|
|
218
|
+
* "another tab took over" (4000) from "the bridge moved to Agentcut, reconnect" (4001).
|
|
219
|
+
*/
|
|
220
|
+
close(code) {
|
|
221
|
+
if (this.closed)
|
|
222
|
+
return;
|
|
223
|
+
this.closed = true;
|
|
224
|
+
debugLog(`editor disconnected${code ? ` (${code})` : ""}`);
|
|
225
|
+
if (activeEditor === this) {
|
|
226
|
+
activeEditor = null;
|
|
227
|
+
editorSession = null;
|
|
228
|
+
extension?.onEditorChange?.(false, null);
|
|
229
|
+
for (const [id, pending] of pendingEditorRequests) {
|
|
230
|
+
clearTimeout(pending.timer);
|
|
231
|
+
pending.reject(new Error("The Agentcut page disconnected."));
|
|
232
|
+
pendingEditorRequests.delete(id);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (code) {
|
|
236
|
+
const frame = Buffer.from([0x88, 2, (code >> 8) & 0xff, code & 0xff]);
|
|
237
|
+
this.socket.end(frame);
|
|
238
|
+
setTimeout(() => this.socket.destroy(), 1000).unref();
|
|
239
|
+
}
|
|
240
|
+
else {
|
|
241
|
+
this.socket.destroy();
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
sendText(text) {
|
|
245
|
+
if (this.closed)
|
|
246
|
+
return;
|
|
247
|
+
const payload = Buffer.from(text);
|
|
248
|
+
let header;
|
|
249
|
+
if (payload.length < 126) {
|
|
250
|
+
header = Buffer.from([0x81, payload.length]);
|
|
251
|
+
}
|
|
252
|
+
else if (payload.length <= 0xffff) {
|
|
253
|
+
header = Buffer.alloc(4);
|
|
254
|
+
header[0] = 0x81;
|
|
255
|
+
header[1] = 126;
|
|
256
|
+
header.writeUInt16BE(payload.length, 2);
|
|
257
|
+
}
|
|
258
|
+
else {
|
|
259
|
+
header = Buffer.alloc(10);
|
|
260
|
+
header[0] = 0x81;
|
|
261
|
+
header[1] = 127;
|
|
262
|
+
header.writeBigUInt64BE(BigInt(payload.length), 2);
|
|
263
|
+
}
|
|
264
|
+
this.socket.write(Buffer.concat([header, payload]));
|
|
265
|
+
}
|
|
266
|
+
read(chunk) {
|
|
267
|
+
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
268
|
+
while (this.buffer.length >= 2) {
|
|
269
|
+
const first = this.buffer[0];
|
|
270
|
+
const second = this.buffer[1];
|
|
271
|
+
const fin = (first & 0x80) !== 0;
|
|
272
|
+
const opcode = first & 0x0f;
|
|
273
|
+
const masked = (second & 0x80) !== 0;
|
|
274
|
+
let length = second & 0x7f;
|
|
275
|
+
let offset = 2;
|
|
276
|
+
if (length === 126) {
|
|
277
|
+
if (this.buffer.length < offset + 2)
|
|
278
|
+
return;
|
|
279
|
+
length = this.buffer.readUInt16BE(offset);
|
|
280
|
+
offset += 2;
|
|
281
|
+
}
|
|
282
|
+
else if (length === 127) {
|
|
283
|
+
if (this.buffer.length < offset + 8)
|
|
284
|
+
return;
|
|
285
|
+
length = Number(this.buffer.readBigUInt64BE(offset));
|
|
286
|
+
offset += 8;
|
|
287
|
+
}
|
|
288
|
+
if (length > MAX_WS_MESSAGE_BYTES) {
|
|
289
|
+
debugLog(`ws frame length ${length} exceeds cap; closing`);
|
|
290
|
+
this.close();
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
const maskLength = masked ? 4 : 0;
|
|
294
|
+
const frameEnd = offset + maskLength + length;
|
|
295
|
+
if (this.buffer.length < frameEnd)
|
|
296
|
+
return;
|
|
297
|
+
const mask = masked ? this.buffer.subarray(offset, offset + 4) : null;
|
|
298
|
+
offset += maskLength;
|
|
299
|
+
const payload = Buffer.from(this.buffer.subarray(offset, offset + length));
|
|
300
|
+
this.buffer = this.buffer.subarray(frameEnd);
|
|
301
|
+
if (mask) {
|
|
302
|
+
for (let index = 0; index < payload.length; index += 1) {
|
|
303
|
+
payload[index] ^= mask[index % 4];
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
// Control frames (0x8-0xF) are never fragmented and may be interleaved
|
|
307
|
+
// between data fragments.
|
|
308
|
+
if (opcode === 0x8) {
|
|
309
|
+
this.close();
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
if (opcode === 0x9) {
|
|
313
|
+
this.sendPong(payload);
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
if (opcode === 0xa) {
|
|
317
|
+
continue; // pong; nothing to do
|
|
318
|
+
}
|
|
319
|
+
// Data frames: 0x1 text, 0x2 binary, 0x0 continuation. Reassemble across
|
|
320
|
+
// fragments so large editor responses (export MP4, captured PNG) survive a
|
|
321
|
+
// multi-frame send.
|
|
322
|
+
if (opcode === 0x1 || opcode === 0x2) {
|
|
323
|
+
this.fragments = [payload];
|
|
324
|
+
this.fragmentOpcode = opcode;
|
|
325
|
+
}
|
|
326
|
+
else if (opcode === 0x0) {
|
|
327
|
+
if (this.fragments.length === 0) {
|
|
328
|
+
debugLog("unexpected continuation frame with no message in progress");
|
|
329
|
+
this.close();
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
this.fragments.push(payload);
|
|
333
|
+
const total = this.fragments.reduce((sum, part) => sum + part.length, 0);
|
|
334
|
+
if (total > MAX_WS_MESSAGE_BYTES) {
|
|
335
|
+
debugLog(`ws fragmented message ${total} exceeds cap; closing`);
|
|
336
|
+
this.close();
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
else {
|
|
341
|
+
debugLog(`ignoring unsupported ws opcode 0x${opcode.toString(16)}`);
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
if (!fin)
|
|
345
|
+
continue; // more fragments to come
|
|
346
|
+
const message = Buffer.concat(this.fragments);
|
|
347
|
+
const completedOpcode = this.fragmentOpcode;
|
|
348
|
+
this.fragments = [];
|
|
349
|
+
this.fragmentOpcode = 0;
|
|
350
|
+
if (completedOpcode === 0x1)
|
|
351
|
+
this.handleText(message.toString("utf8"));
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
async handleStudioRequest(message) {
|
|
355
|
+
const id = message.id;
|
|
356
|
+
if (typeof id !== "string")
|
|
357
|
+
return;
|
|
358
|
+
if (!extension) {
|
|
359
|
+
this.sendJson({
|
|
360
|
+
type: "studio.response",
|
|
361
|
+
id,
|
|
362
|
+
error: { message: "Agentcut is not running. Start it with: npx -y agentcut" },
|
|
363
|
+
});
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
try {
|
|
367
|
+
const result = await extension.handlePageRequest(String(message.method ?? ""), message.params ?? {});
|
|
368
|
+
this.sendJson({ type: "studio.response", id, result });
|
|
369
|
+
}
|
|
370
|
+
catch (error) {
|
|
371
|
+
this.sendJson({
|
|
372
|
+
type: "studio.response",
|
|
373
|
+
id,
|
|
374
|
+
error: {
|
|
375
|
+
message: error instanceof Error ? error.message : String(error),
|
|
376
|
+
code: error?.code,
|
|
377
|
+
},
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
sendPong(payload) {
|
|
382
|
+
if (this.closed)
|
|
383
|
+
return;
|
|
384
|
+
// Control frame payloads are capped at 125 bytes; echo what fits.
|
|
385
|
+
const length = Math.min(payload.length, 125);
|
|
386
|
+
const header = Buffer.from([0x8a, length]);
|
|
387
|
+
this.socket.write(Buffer.concat([header, payload.subarray(0, length)]));
|
|
388
|
+
}
|
|
389
|
+
handleText(text) {
|
|
390
|
+
let message;
|
|
391
|
+
try {
|
|
392
|
+
message = JSON.parse(text);
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
if (message &&
|
|
398
|
+
typeof message === "object" &&
|
|
399
|
+
message.type === "hello") {
|
|
400
|
+
editorSession = message.session;
|
|
401
|
+
debugLog(`editor hello ${JSON.stringify(editorSession)}`);
|
|
402
|
+
extension?.onEditorChange?.(true, editorSession);
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
if (message &&
|
|
406
|
+
typeof message === "object" &&
|
|
407
|
+
message.type === "studio.request") {
|
|
408
|
+
void this.handleStudioRequest(message);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
const response = message;
|
|
412
|
+
if (typeof response.id !== "string")
|
|
413
|
+
return;
|
|
414
|
+
const pending = pendingEditorRequests.get(response.id);
|
|
415
|
+
if (!pending)
|
|
416
|
+
return;
|
|
417
|
+
clearTimeout(pending.timer);
|
|
418
|
+
pendingEditorRequests.delete(response.id);
|
|
419
|
+
if (response.error) {
|
|
420
|
+
pending.reject(new Error(String(response.error.message ?? "Editor error.")));
|
|
421
|
+
}
|
|
422
|
+
else {
|
|
423
|
+
pending.resolve(response.result);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
/** Page close codes (see WebSocketConnection.close). */
|
|
428
|
+
export const CLOSE_REPLACED = 4000;
|
|
429
|
+
export const CLOSE_HANDOFF = 4001;
|
|
430
|
+
/**
|
|
431
|
+
* After this process hands the port to Agentcut it must not grab it straight back while
|
|
432
|
+
* the studio is still binding. Until then calls go to whoever owns the port.
|
|
433
|
+
*/
|
|
434
|
+
let handedOffUntil = 0;
|
|
435
|
+
export function getBridgeStatus() {
|
|
436
|
+
const { port } = getConfig();
|
|
437
|
+
return {
|
|
438
|
+
ok: true,
|
|
439
|
+
/** Agentcut's helper owns this bridge (it can't hand the port over). */
|
|
440
|
+
studio: Boolean(extension),
|
|
441
|
+
version: PACKAGE_VERSION,
|
|
442
|
+
connected: Boolean(activeEditor && !activeEditor.closed),
|
|
443
|
+
port,
|
|
444
|
+
path: WS_PATH,
|
|
445
|
+
session: editorSession,
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
async function fetchBridgeStatus() {
|
|
449
|
+
const { bridgeBaseUrl } = getConfig();
|
|
450
|
+
const response = await fetch(`${bridgeBaseUrl}/status`, {
|
|
451
|
+
signal: AbortSignal.timeout(BRIDGE_PROBE_TIMEOUT_MS),
|
|
452
|
+
});
|
|
453
|
+
if (!response.ok)
|
|
454
|
+
throw new Error(`Bridge status failed: ${response.status}`);
|
|
455
|
+
return response.json();
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* POST /call on the bridge another process owns. Uses node:http rather than fetch: fetch (undici) gives
|
|
459
|
+
* up waiting for response headers after 300 s, and exports or long captures can take longer.
|
|
460
|
+
*/
|
|
461
|
+
function callExternalBridge(method, params, timeoutMs) {
|
|
462
|
+
const { host, port } = getConfig();
|
|
463
|
+
const payload = JSON.stringify({ method, params, timeoutMs });
|
|
464
|
+
return new Promise((resolve, reject) => {
|
|
465
|
+
const req = httpRequest({
|
|
466
|
+
host,
|
|
467
|
+
port,
|
|
468
|
+
path: "/call",
|
|
469
|
+
method: "POST",
|
|
470
|
+
headers: { "content-type": "application/json", "content-length": Buffer.byteLength(payload) },
|
|
471
|
+
}, (res) => {
|
|
472
|
+
const chunks = [];
|
|
473
|
+
res.on("data", (chunk) => chunks.push(chunk));
|
|
474
|
+
res.on("end", () => {
|
|
475
|
+
clearTimeout(timer);
|
|
476
|
+
try {
|
|
477
|
+
const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
478
|
+
if ((res.statusCode ?? 500) >= 400 || body.error) {
|
|
479
|
+
reject(new Error(body.error ?? `Bridge call failed: ${res.statusCode}`));
|
|
480
|
+
}
|
|
481
|
+
else {
|
|
482
|
+
resolve(body.result);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
catch (error) {
|
|
486
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
487
|
+
}
|
|
488
|
+
});
|
|
489
|
+
});
|
|
490
|
+
const timer = setTimeout(() => req.destroy(new Error(`Bridge call "${method}" timed out.`)), timeoutMs + 5_000);
|
|
491
|
+
req.on("error", (error) => {
|
|
492
|
+
clearTimeout(timer);
|
|
493
|
+
reject(error);
|
|
494
|
+
});
|
|
495
|
+
req.end(payload);
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
export async function callEditor(method, params, options) {
|
|
499
|
+
const timeoutMs = options?.timeoutMs ?? EDITOR_CALL_TIMEOUT_MS;
|
|
500
|
+
const local = extension?.handleLocalCall(method, params);
|
|
501
|
+
if (local)
|
|
502
|
+
return local;
|
|
503
|
+
await ensureBridge();
|
|
504
|
+
if (!activeEditor || activeEditor.closed) {
|
|
505
|
+
if (!serverPromise) {
|
|
506
|
+
return callExternalBridge(method, params, timeoutMs);
|
|
507
|
+
}
|
|
508
|
+
throw new Error("No Agentcut page is connected. Open Agentcut in your browser.");
|
|
509
|
+
}
|
|
510
|
+
const id = `agent_${++editorRequestCounter}`;
|
|
511
|
+
activeEditor.sendJson({ id, method, params });
|
|
512
|
+
return new Promise((resolve, reject) => {
|
|
513
|
+
const timer = setTimeout(() => {
|
|
514
|
+
pendingEditorRequests.delete(id);
|
|
515
|
+
reject(new Error(`The Agentcut page did not answer "${method}" in time.`));
|
|
516
|
+
}, timeoutMs);
|
|
517
|
+
pendingEditorRequests.set(id, { resolve, reject, timer });
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
export async function ensureBridge() {
|
|
521
|
+
if (!serverPromise) {
|
|
522
|
+
try {
|
|
523
|
+
return await fetchBridgeStatus();
|
|
524
|
+
}
|
|
525
|
+
catch { }
|
|
526
|
+
if (Date.now() < handedOffUntil) {
|
|
527
|
+
throw new Error("The bridge is restarting; try again in a moment.");
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
if (serverPromise) {
|
|
531
|
+
await serverPromise;
|
|
532
|
+
return getBridgeStatus();
|
|
533
|
+
}
|
|
534
|
+
serverPromise = startBridgeServer();
|
|
535
|
+
try {
|
|
536
|
+
await serverPromise;
|
|
537
|
+
}
|
|
538
|
+
catch (error) {
|
|
539
|
+
// Starting our own bridge failed, most likely because another MCP instance
|
|
540
|
+
// already bound the port (EADDRINUSE). Clear the rejected promise so future
|
|
541
|
+
// calls re-probe, and fall back to whoever owns the bridge right now.
|
|
542
|
+
serverPromise = null;
|
|
543
|
+
debugLog(`bridge startup failed, falling back to existing bridge ${error instanceof Error ? error.message : String(error)}`);
|
|
544
|
+
return await fetchBridgeStatus();
|
|
545
|
+
}
|
|
546
|
+
return getBridgeStatus();
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* Start the bridge in this process and fail if the port is taken. Used by
|
|
550
|
+
* `agentcut`, which must own the bridge.
|
|
551
|
+
*/
|
|
552
|
+
export async function startOwnedBridge() {
|
|
553
|
+
try {
|
|
554
|
+
return await tryStartBridge();
|
|
555
|
+
}
|
|
556
|
+
catch (error) {
|
|
557
|
+
if (error.code !== "EADDRINUSE")
|
|
558
|
+
throw error;
|
|
559
|
+
}
|
|
560
|
+
// Someone owns the port. Another Agentcut can't be moved; a plain Agentcut MCP
|
|
561
|
+
// server (the editor tools inside a Claude session) hands it over and forwards from then on.
|
|
562
|
+
const { bridgeBaseUrl } = getConfig();
|
|
563
|
+
const owner = (await fetchBridgeStatus().catch(() => null));
|
|
564
|
+
if (owner?.studio)
|
|
565
|
+
throw new BridgeTakeoverError("studio_running");
|
|
566
|
+
const handoff = await fetch(`${bridgeBaseUrl}/handoff`, {
|
|
567
|
+
method: "POST",
|
|
568
|
+
signal: AbortSignal.timeout(BRIDGE_PROBE_TIMEOUT_MS),
|
|
569
|
+
}).catch(() => null);
|
|
570
|
+
if (!handoff?.ok)
|
|
571
|
+
throw new BridgeTakeoverError(owner ? "old_mcp" : "unknown_owner");
|
|
572
|
+
const deadline = Date.now() + 8_000;
|
|
573
|
+
for (;;) {
|
|
574
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
575
|
+
try {
|
|
576
|
+
return await tryStartBridge();
|
|
577
|
+
}
|
|
578
|
+
catch (error) {
|
|
579
|
+
if (error.code !== "EADDRINUSE" || Date.now() > deadline)
|
|
580
|
+
throw error;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
export class BridgeTakeoverError extends Error {
|
|
585
|
+
reason;
|
|
586
|
+
constructor(reason) {
|
|
587
|
+
super(reason);
|
|
588
|
+
this.reason = reason;
|
|
589
|
+
this.name = "BridgeTakeoverError";
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
async function tryStartBridge() {
|
|
593
|
+
if (!serverPromise)
|
|
594
|
+
serverPromise = startBridgeServer();
|
|
595
|
+
try {
|
|
596
|
+
return await serverPromise;
|
|
597
|
+
}
|
|
598
|
+
catch (error) {
|
|
599
|
+
serverPromise = null;
|
|
600
|
+
throw error;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
async function startBridgeServer() {
|
|
604
|
+
const { host, port } = getConfig();
|
|
605
|
+
const server = createServer(async (request, response) => {
|
|
606
|
+
if (!isLocalRequest(request)) {
|
|
607
|
+
sendJsonResponse(response, 403, { error: "Forbidden" });
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
if (extension && !extension.isOriginAllowed(headerValue(request.headers.origin))) {
|
|
611
|
+
sendJsonResponse(response, 403, { error: "Origin not allowed" });
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
try {
|
|
615
|
+
if (extension && (await extension.handleHttp(request, response)))
|
|
616
|
+
return;
|
|
617
|
+
// Agentcut's helper asks a plain MCP bridge for the port: close the page
|
|
618
|
+
// (it reconnects to the studio) and forward this process's calls from now on.
|
|
619
|
+
if (request.method === "POST" && request.url === "/handoff" && !extension) {
|
|
620
|
+
sendJsonResponse(response, 200, { ok: true });
|
|
621
|
+
handedOffUntil = Date.now() + 10_000;
|
|
622
|
+
serverPromise = null;
|
|
623
|
+
activeEditor?.close(CLOSE_HANDOFF);
|
|
624
|
+
server.close();
|
|
625
|
+
server.closeAllConnections?.();
|
|
626
|
+
debugLog("bridge handed off to Agentcut");
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
if (request.method === "GET" && request.url === "/status") {
|
|
630
|
+
sendJsonResponse(response, 200, getBridgeStatus());
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
if (request.method === "POST" && request.url === "/call") {
|
|
634
|
+
const body = await readJsonBody(request);
|
|
635
|
+
const method = String(body.method ?? "");
|
|
636
|
+
const timeoutMs = typeof body.timeoutMs === "number" && body.timeoutMs > 0
|
|
637
|
+
? Math.min(body.timeoutMs, 2 * 60 * 60 * 1000)
|
|
638
|
+
: undefined;
|
|
639
|
+
const result = persistAgentFrameResult(await callEditor(method, body.params, { timeoutMs }));
|
|
640
|
+
sendJsonResponse(response, 200, { result });
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
sendJsonResponse(response, 404, { error: "Not found" });
|
|
644
|
+
}
|
|
645
|
+
catch (error) {
|
|
646
|
+
sendJsonResponse(response, 500, {
|
|
647
|
+
error: error instanceof Error ? error.message : "Unknown bridge error.",
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
});
|
|
651
|
+
server.on("upgrade", (request, socket, head) => {
|
|
652
|
+
debugLog(`upgrade url=${request.url} remote=${request.socket.remoteAddress}`);
|
|
653
|
+
if (request.url !== WS_PATH ||
|
|
654
|
+
!isLocalRequest(request) ||
|
|
655
|
+
request.headers.upgrade?.toLowerCase() !== "websocket" ||
|
|
656
|
+
(extension && !extension.isOriginAllowed(headerValue(request.headers.origin)))) {
|
|
657
|
+
socket.destroy();
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
const key = request.headers["sec-websocket-key"];
|
|
661
|
+
if (typeof key !== "string") {
|
|
662
|
+
socket.destroy();
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
socket.write([
|
|
666
|
+
"HTTP/1.1 101 Switching Protocols",
|
|
667
|
+
"Upgrade: websocket",
|
|
668
|
+
"Connection: Upgrade",
|
|
669
|
+
`Sec-WebSocket-Accept: ${createAcceptKey(key)}`,
|
|
670
|
+
"\r\n",
|
|
671
|
+
].join("\r\n"));
|
|
672
|
+
if (head.length > 0)
|
|
673
|
+
socket.unshift(head);
|
|
674
|
+
activeEditor?.close(CLOSE_REPLACED);
|
|
675
|
+
activeEditor = new WebSocketConnection(socket);
|
|
676
|
+
debugLog("editor connected");
|
|
677
|
+
});
|
|
678
|
+
server.on("error", (error) => {
|
|
679
|
+
debugLog(`bridge server error ${error.message}`);
|
|
680
|
+
});
|
|
681
|
+
await new Promise((resolve, reject) => {
|
|
682
|
+
server.once("error", reject);
|
|
683
|
+
server.listen(port, host, () => {
|
|
684
|
+
server.off("error", reject);
|
|
685
|
+
debugLog(`bridge listening ${host}:${port}${WS_PATH}`);
|
|
686
|
+
resolve();
|
|
687
|
+
});
|
|
688
|
+
});
|
|
689
|
+
return server;
|
|
690
|
+
}
|
|
691
|
+
//# sourceMappingURL=bridge.js.map
|