From 39f54274205471337e3cca92df3f8ceed06b1d5b Mon Sep 17 00:00:00 2001 From: qingnian108 <44261124+qingnian108@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:49:42 +0800 Subject: [PATCH] agent-console 1.3.4: Stop ends the turn at once on ACP, Claude and Codex (#768) Stop now ends the turn at once, and a resend right after it is safe, on all three paths: - ACP (Devin, Cursor, Copilot, OpenCode, Pi, dsh): session/cancel goes as a notification, the local turn ends at once, and a resend waits for the cancel and the previous prompt to settle. - Claude: the result FIFO (turnGen, awaitingResult, skipResultGens) lives on each CLI process, and a replaced CLI's leftover stdout is ignored. After a crash the queue stays open, so the next send resumes with --resume. - Codex: a turn whose turn/start response arrives after Stop is interrupted by its own response id. Run at 0cf12a96 on mote with HOME=$(mktemp -d): - root bun test: 6171 pass, 0 fail; - bun scripts/check.mjs agent-console: ok; - in packages/agent-console: npm ci, npm run check (tsc) and npm run build are ok, daemon/dist is byte-identical to the committed one, and verify:build is OK; - npx vitest run: 68 files, 507 passed, 17 skipped. Broken by hand, then acp-interrupt, claude-cli and codex-interrupt were run again. Each mutant was red: - codex: wasCancelled forced false: 1 fail; - codex: interrupt() no longer ends the local turn: 5 fail; - acp: pendingCancelSettle not awaited: 1 fail; - acp: the late prompt settle ends the turn without the activeTurnId guard: 1 fail; - claude: a replaced CLI's stdout no longer ignored: 1 fail; - claude: interrupt no longer marks its gen in skipResultGens: 2 fail; - claude: a crash closes the queue instead of setting needsRestart: 2 fail. Not tried: a real Claude or Codex CLI. The PR says Devin 3000.11.3 was tried live. Not blocking: a Codex turn/start response that arrives after turn/completed sends an extra turn/interrupt and leaves one staleCodexTurns entry. --- packages/agent-console/daemon/dist/main.js | 233 ++++++++++++++---- .../agent-console/daemon/dist/main.js.map | 2 +- .../daemon/src/agents/manager.ts | 5 +- .../daemon/src/providers/acp/session.ts | 121 +++++++-- .../daemon/src/providers/claude/cli.ts | 6 + .../daemon/src/providers/claude/session.ts | 46 +++- .../daemon/src/providers/codex/session.ts | 121 ++++++--- packages/agent-console/package-lock.json | 4 +- packages/agent-console/package.json | 2 +- .../test/v1/acp-interrupt.test.ts | 180 ++++++++++++++ .../agent-console/test/v1/claude-cli.test.ts | 226 ++++++++++++++++- .../test/v1/codex-interrupt.test.ts | 213 ++++++++++++++++ .../test/v1/fixtures/fake-acp-agent.mjs | 76 +++++- .../test/v1/fixtures/fake-claude.mjs | 73 +++++- .../v1/fixtures/fake-codex-app-server.mjs | 101 ++++++++ .../test/v1/interrupt-audit.test.ts | 24 ++ 16 files changed, 1311 insertions(+), 122 deletions(-) create mode 100644 packages/agent-console/test/v1/acp-interrupt.test.ts create mode 100644 packages/agent-console/test/v1/codex-interrupt.test.ts create mode 100644 packages/agent-console/test/v1/fixtures/fake-codex-app-server.mjs create mode 100644 packages/agent-console/test/v1/interrupt-audit.test.ts diff --git a/packages/agent-console/daemon/dist/main.js b/packages/agent-console/daemon/dist/main.js index 73fff36..e2e5156 100644 --- a/packages/agent-console/daemon/dist/main.js +++ b/packages/agent-console/daemon/dist/main.js @@ -2439,6 +2439,12 @@ var init_cli = __esm({ exited; /** The answer to initialize (commands, models, account …), null when it failed */ initialized; + /** Monotonic turn gen for THIS process (dies with the CLI). */ + turnGen = 0; + /** Turn gens still waiting for a `result` from THIS process (dies with the CLI). */ + awaitingResult = []; + /** Gens already ended locally on interrupt; their late `result` must be dropped. */ + skipResultGens = /* @__PURE__ */ new Set(); child; buf = ""; seq = 0; @@ -2648,7 +2654,14 @@ var init_session = __esm({ } async pump(cli) { for await (const m of cli.messages) { - for (const ev of mapSdkMessage(m, this.st, this.o.cwd)) this.emit(ev); + if (this.cli !== cli) continue; + for (const ev of mapSdkMessage(m, this.st, this.o.cwd)) { + if (ev.type === "turn_ended") { + const g = cli.awaitingResult.shift(); + if (g != null && cli.skipResultGens.delete(g)) continue; + } + this.emit(ev); + } } const exit = await cli.exited; if (this.closed || this.stopping.has(cli)) return; @@ -2659,7 +2672,6 @@ var init_session = __esm({ this.turnId = null; if (this.cli === cli) { this.needsRestart = true; - this.q.close(); } } emit(ev) { @@ -2673,6 +2685,8 @@ var init_session = __esm({ if (this.needsRestart) await this.restart(); const cli = this.ensureCli(); this.turnNum++; + const gen = ++cli.turnGen; + cli.awaitingResult.push(gen); this.turnId = "u_" + Date.now().toString(36) + "_" + this.turnNum; this.st.sawInterrupt = false; this.emit({ @@ -2826,7 +2840,17 @@ var init_session = __esm({ } this.pending.clear(); const cli = this.cli; - if (!cli || !cli.alive) return; + const endLocal = () => { + if (this.turnId) { + const gen = cli?.awaitingResult.at(-1); + if (gen != null) cli.skipResultGens.add(gen); + this.emit({ type: "turn_ended", turnId: this.turnId, status: "interrupted" }); + } + }; + if (!cli || !cli.alive) { + endLocal(); + return; + } try { await cli.interrupt(); } catch (e) { @@ -2834,8 +2858,12 @@ var init_session = __esm({ this.stopping.add(cli); this.needsRestart = true; void cli.close(500); - if (this.turnId) this.emit({ type: "turn_ended", turnId: this.turnId, status: "interrupted" }); + if (this.turnId) { + this.emit({ type: "turn_ended", turnId: this.turnId, status: "interrupted" }); + } + return; } + endLocal(); } async setModel(model) { this.o.model = model; @@ -3853,18 +3881,32 @@ var init_session2 = __esm({ pending = /* @__PURE__ */ new Map(); closed = false; started = null; - interruptWanted = false; ourTurnId = null; // The current turn's turnId in the timeline (generated on send) + /** Codex turn ids whose late started/completed/deltas must be ignored. */ staleCodexTurns = /* @__PURE__ */ new Set(); codexSlash = null; emit(ev) { if (ev.type === "turn_ended") { - if (ev.turnId && this.staleCodexTurns.delete(ev.turnId)) return; - if (this.ourTurnId) ev.turnId = this.ourTurnId; - this.ourTurnId = null; - this.st.currentTurnId = null; - this.interruptWanted = false; + if (ev.turnId && this.staleCodexTurns.delete(ev.turnId)) { + if (this.st.currentTurnId === ev.turnId) this.st.currentTurnId = null; + return; + } + if (this.ourTurnId) { + if (!ev.turnId || ev.turnId === this.st.currentTurnId || ev.turnId === this.ourTurnId) { + ev.turnId = this.ourTurnId; + } else { + return; + } + this.ourTurnId = null; + this.st.currentTurnId = null; + } else { + if (ev.turnId) { + this.staleCodexTurns.delete(ev.turnId); + if (this.st.currentTurnId === ev.turnId) this.st.currentTurnId = null; + } + return; + } } this.q.push(ev); } @@ -3880,8 +3922,18 @@ var init_session2 = __esm({ ); this.rpc = rpc; rpc.onNotification = (m, p) => { + const turnFromParams = () => { + const turn = p?.turn; + if (typeof turn?.id === "string") return turn.id; + if (typeof p.turnId === "string") return p.turnId; + return null; + }; + const tid = turnFromParams(); + if (tid && this.staleCodexTurns.has(tid)) { + if (m === "turn/completed") this.staleCodexTurns.delete(tid); + return; + } for (const ev of mapNotification(m, p, this.st)) this.emit(ev); - if (this.interruptWanted && this.st.currentTurnId) void this.interrupt(); }; rpc.onServerRequest = (m, p) => this.onServerRequest(m, p); rpc.onExit = () => { @@ -3945,7 +3997,6 @@ var init_session2 = __esm({ this.codexSlash = entries; const wireText = expandCodexSlash(input.text, entries); const { items, warnings } = await buildCodexInput(wireText, input.images ?? []); - this.interruptWanted = false; const turnId = "u_" + Date.now().toString(36) + "_" + rid3(); if (this.ourTurnId && this.st.currentTurnId) this.staleCodexTurns.add(this.st.currentTurnId); this.ourTurnId = turnId; @@ -3959,7 +4010,7 @@ var init_session2 = __esm({ }); for (const w of warnings) this.emit({ type: "notice", level: "warn", message: tr("notice.attachmentIssue", { detail: w }) }); try { - await rpc.request("turn/start", { + const res = await rpc.request("turn/start", { threadId: this.sessionThreadId ?? void 0, input: items, model: this.o.model, @@ -3967,7 +4018,26 @@ var init_session2 = __esm({ approvalPolicy: preset.approvalPolicy, sandboxPolicy: preset.sandboxPolicy }); + const codexTurnId = typeof res?.turn?.id === "string" ? res.turn.id : null; + if (!codexTurnId) return; + const wasCancelled = this.ourTurnId !== turnId; + if (wasCancelled) { + this.staleCodexTurns.add(codexTurnId); + try { + await rpc.request( + "turn/interrupt", + { threadId: this.threadId(), turnId: codexTurnId }, + 5e3 + ); + } catch (e) { + const msg = String(e?.message ?? e); + if (!/idle|not running|no.*turn/i.test(msg)) log("warn", "codex interrupt \u5931\u8D25", { err: msg }); + } + return; + } + this.st.currentTurnId = codexTurnId; } catch (e) { + if (this.ourTurnId !== turnId) return; this.emit({ type: "turn_ended", turnId, @@ -3993,24 +4063,30 @@ var init_session2 = __esm({ async interrupt() { for (const [, p] of this.pending) p.resolve({ cancelled: true }); this.pending.clear(); - if (!this.rpc) return; - if (!this.st.currentTurnId) { - this.interruptWanted = true; + const localTurn = this.ourTurnId; + const codexTurn = this.st.currentTurnId; + if (!this.rpc) { + if (localTurn) this.emit({ type: "turn_ended", turnId: localTurn, status: "interrupted" }); return; } - this.interruptWanted = false; - try { - await this.rpc.request( - "turn/interrupt", - { threadId: this.threadId(), turnId: this.st.currentTurnId }, - 5e3 - ); - } catch (e) { - const msg = String(e?.message ?? e); - if (!/idle|not running|no.*turn/i.test(msg)) { - log("warn", "codex interrupt \u5931\u8D25", { err: msg }); + if (codexTurn) { + this.staleCodexTurns.add(codexTurn); + try { + await this.rpc.request( + "turn/interrupt", + { threadId: this.threadId(), turnId: codexTurn }, + 5e3 + ); + } catch (e) { + const msg = String(e?.message ?? e); + if (!/idle|not running|no.*turn/i.test(msg)) { + log("warn", "codex interrupt \u5931\u8D25", { err: msg }); + } } } + if (localTurn && this.ourTurnId === localTurn) { + this.emit({ type: "turn_ended", turnId: localTurn, status: "interrupted" }); + } } threadId() { return this.sessionThreadId ?? void 0; @@ -4777,6 +4853,11 @@ var init_session3 = __esm({ turnId = null; turnNum = 0; running = false; + /** Current wire session/prompt settle (never rejects) — interrupt waits for it before the next prompt. */ + inFlightPrompt = null; + /** After Stop: notify(cancel) + previous prompt settle + one macrotask, so pumpUpdates drains before next prompt(). */ + pendingCancelSettle = null; + closeWaiters = []; permPending = /* @__PURE__ */ new Map(); mapCtx = newMapCtx(); modelConfigId = null; @@ -5058,12 +5139,12 @@ var init_session3 = __esm({ await this.ready(); if (this.running) throw new Error("\u5F53\u524D\u8F6E\u6B21\u5C1A\u672A\u7ED3\u675F"); this.turnNum++; - this.turnId = "u_" + Date.now().toString(36) + "_" + this.turnNum; - this.mapCtx = newMapCtx(); + const turnId = "u_" + Date.now().toString(36) + "_" + this.turnNum; + this.turnId = turnId; this.running = true; this.q.push({ type: "turn_started", - turnId: this.turnId, + turnId, model: this.o.model, mode: this.o.mode, effort: this.o.effort @@ -5072,10 +5153,11 @@ var init_session3 = __esm({ const attachments = input.images ?? []; if (!text && !attachments.length) { this.running = false; - this.q.push({ type: "turn_ended", turnId: this.turnId, status: "completed" }); + this.q.push({ type: "turn_ended", turnId, status: "completed" }); return; } const built = await buildAcpPrompt(text, attachments, this.promptCaps, input.mentions ?? []); + if (this.closed || !this.running || this.turnId !== turnId) return; const agent = this.o.providerName ?? this.o.binName; if (built.imagesByPath.length && !this.promptCaps.image) { const switched = this.o.imagesFollowStartModel && this.initCaps.image && this.o.model !== this.startModel; @@ -5083,19 +5165,65 @@ var init_session3 = __esm({ } for (const w of built.warnings) this.q.push({ type: "notice", level: "warn", message: tr("notice.attachmentIssue", { detail: w }) }); if (!built.blocks.length) { - this.running = false; - this.q.push({ type: "turn_ended", turnId: this.turnId, status: "completed" }); + if (this.turnId === turnId && this.running) { + this.running = false; + this.q.push({ type: "turn_ended", turnId, status: "completed" }); + } return; } - void this.runTurn(built.blocks); + void this.runTurn(turnId, built.blocks); } - // Send this turn's prompt; reading updates is the job of the persistent pumpUpdates() (following Paseo: session/update is handled at session level) - async runTurn(prompt) { - this.activeTurnId = this.turnId; + waitCloseOrTimeout(ms) { + if (this.closed) return Promise.resolve(); + return new Promise((resolve4) => { + const t = setTimeout(() => { + this.closeWaiters = this.closeWaiters.filter((w) => w !== done); + resolve4(); + }, ms); + const done = () => { + clearTimeout(t); + resolve4(); + }; + this.closeWaiters.push(done); + }); + } + // Send this turn's prompt; session/update still flows through pumpUpdates, but ending the turn is tied + // to this prompt() promise so a JSON-RPC error on a cancelled prompt cannot leave a leftover counter. + // After Stop, wait for pendingCancelSettle before activating Turn N+1 on the wire (Devin cancels an + // overlapping session/prompt that arrives while the previous one is still unwinding). + async runTurn(turnId, prompt) { + const pending = this.pendingCancelSettle; + if (pending) { + await Promise.race([pending, this.waitCloseOrTimeout(2e3)]); + if (this.pendingCancelSettle === pending) this.pendingCancelSettle = null; + if (this.closed || !this.running || this.turnId !== turnId) return; + } + this.mapCtx = newMapCtx(); + this.activeTurnId = turnId; this.wakePump?.(); this.wakePump = null; - this.active.prompt(prompt).catch(() => { + const req = this.active.prompt(prompt); + const settle = req.then(() => { + }, () => { }); + this.inFlightPrompt = settle; + try { + const res = await req; + if (this.activeTurnId === turnId) { + this.endTurn(stopToTurnEnd(res.stopReason, turnId)); + } + } catch (e) { + if (this.activeTurnId === turnId) { + this.endTurn({ + type: "turn_ended", + turnId, + status: "failed", + error: String(e?.message ?? e) + }); + } + } finally { + if (this.inFlightPrompt === settle) this.inFlightPrompt = null; + } } endTurn(ev) { for (const id2 of [...this.permPending.keys()]) this.cancelPerm(id2); @@ -5117,10 +5245,6 @@ var init_session3 = __esm({ msg = await session.nextUpdate(); } catch (e) { if (this.closed) return; - const turnId = this.activeTurnId; - if (turnId) { - this.endTurn({ type: "turn_ended", turnId, status: "failed", error: String(e?.message ?? e) }); - } await new Promise((r) => this.wakePump = r); continue; } @@ -5132,19 +5256,30 @@ var init_session3 = __esm({ } if (!this.activeTurnId) continue; for (const ev of mapSessionUpdate(u, this.mapCtx)) this.q.push(ev); - } else if (this.activeTurnId) { - this.endTurn(stopToTurnEnd(msg.stopReason, this.activeTurnId)); + } else { + continue; } } } async interrupt() { await this.ready(); if (!this.ctx || !this.active) return; - try { - await this.ctx.request(methods2.agent.session.cancel, { sessionId: this.active.sessionId }); - } catch (e) { + const notifyP = this.ctx.notify(methods2.agent.session.cancel, { sessionId: this.active.sessionId }).catch((e) => { log("info", `ACP cancel: ${String(e)}`); + }); + const prevSettle = this.inFlightPrompt ?? Promise.resolve(); + this.pendingCancelSettle = Promise.all([notifyP, prevSettle]).then( + () => new Promise((r) => setTimeout(r, 0)) + ); + if (this.running) { + const turnId = this.activeTurnId ?? this.turnId; + if (turnId) { + this.endTurn({ type: "turn_ended", turnId, status: "interrupted" }); + } else { + this.running = false; + } } + await notifyP; } async setModel(model) { this.o.model = model; @@ -5177,6 +5312,7 @@ var init_session3 = __esm({ } async close() { this.closed = true; + for (const w of this.closeWaiters.splice(0)) w(); this.wakePump?.(); this.settleCommands(); for (const r of this.permPending.values()) r({ cancelled: true }); @@ -9066,7 +9202,8 @@ var AgentManager = class { await this.setStatus(threadId, "running"); try { const images = await this.resolveAttachments(attachmentRefs); - await rt.session.send({ text: withMentions(text, mentions), images, mentions }); + const payload = { text: withMentions(text, mentions), images, mentions }; + await rt.session.send(payload); } catch (e) { const msg = String(e?.message ?? e); await this.appendRaw(threadId, { type: "notice", level: "error", message: tr("notice.sendFailed", { detail: msg }) }); diff --git a/packages/agent-console/daemon/dist/main.js.map b/packages/agent-console/daemon/dist/main.js.map index 3570bdf..ab519fd 100644 --- a/packages/agent-console/daemon/dist/main.js.map +++ b/packages/agent-console/daemon/dist/main.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/log.ts","../src/security.ts","../src/util/i18n.ts","../src/util/paths.ts","../src/util/queue.ts","../src/agents/diff.ts","../src/providers/slash.ts","../src/providers/mock.ts","../../lib/pathscan.mjs","../src/util/gitBash.ts","../src/util/agentShell.ts","../src/util/bin.ts","../src/agents/kinds.ts","../src/providers/claude/map.ts","../src/util/attachmentRefs.ts","../src/util/attachmentKinds.ts","../src/providers/claude/content.ts","../src/providers/launch.ts","../src/util/decode.ts","../src/providers/claude/cli.ts","../src/providers/claude/session.ts","../src/providers/claude/models.ts","../src/history/import.ts","../src/providers/claude/provider.ts","../src/history/codex.ts","../src/providers/codex/rpc.ts","../src/providers/codex/input.ts","../src/providers/codex/map.ts","../src/providers/codex/commands.ts","../src/providers/codex/session.ts","../src/providers/types.ts","../src/providers/codex/provider.ts","../src/providers/catalog.ts","../src/providers/acp/spawn.ts","../src/providers/acp/clientHandlers.ts","../src/providers/acp/mapUpdate.ts","../src/providers/acp/promptCaps.ts","../src/providers/acp/sessionCaps.ts","../src/providers/acp/prompt.ts","../src/providers/acp/session.ts","../src/providers/acp/provider.ts","../src/providers/acp/dsh.ts","../src/providers/acp/probe.ts","../src/providers/acp/specs.ts","../src/providers/registry.ts","../src/providers/enabled.ts","../src/util/pickFolderWin.ts","../src/util/pickFolder.ts","../src/providers/magpieGateway.ts","../src/providers/infoCache.ts","../src/providers/modes.ts","../src/providers/autoApprove.ts","../src/migrate/autoApprove13.ts","../src/util/mentions.ts","../src/preview/url.ts","../src/util/openExternal.ts","../src/preview/inject.ts","../src/preview/proxy.ts","../src/preview/host.ts","../src/ws/methods.ts","../src/util/atomic.ts","../src/store/settings.ts","../src/util/jsonl.ts","../src/migrate/legacy.ts","../src/providers/warm.ts","../src/main.ts","../src/config.ts","../src/util/buildStamp.ts","../src/http.ts","../src/store/attachments.ts","../src/store/projects.ts","../src/store/threads.ts","../src/ws/gateway.ts","../src/agents/manager.ts","../src/timeline/coalescer.ts","../src/git/service.ts","../src/files/service.ts","../src/terminal/service.ts","../src/util/proc.ts","../src/preview/ports.ts"],"sourcesContent":["// Simple logging: writes dataDir/logs/daemon-YYYY-MM-DD.log (kept 7 days) and to the console.\nimport { appendFileSync, mkdirSync, readdirSync, rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nlet logDir = \"\";\nlet today = \"\";\nlet logFile = \"\";\n\nfunction fileName(d: Date): string {\n const p = (n: number) => String(n).padStart(2, \"0\");\n return `daemon-${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}.log`;\n}\n\nexport function initLog(dataDir: string): void {\n logDir = join(dataDir, \"logs\");\n mkdirSync(logDir, { recursive: true });\n // Keep 7 days\n try {\n const keep = new Set();\n const now = new Date();\n for (let i = 0; i < 7; i++) {\n keep.add(fileName(new Date(now.getTime() - i * 86400000)));\n }\n for (const f of readdirSync(logDir)) {\n if (/^daemon-\\d{4}-\\d{2}-\\d{2}\\.log$/.test(f) && !keep.has(f)) {\n rmSync(join(logDir, f), { force: true });\n }\n }\n } catch {}\n}\n\n// The console is a pipe to the plugin host. When the host is killed hard, the reader is gone and a write fails with EPIPE\n// (asynchronously, as an 'error' event on the stream): without a listener that becomes an uncaughtException. Once that happens\n// the console is dropped and only the log file is written.\nlet consoleGone = false;\nlet guarded = false;\nfunction guardConsole(): void {\n if (guarded) return;\n guarded = true;\n for (const stream of [process.stdout, process.stderr]) {\n // EPIPE, EIO, ERR_STREAM_DESTROYED…: any write error means the reader is gone; logging must never take the daemon down\n stream?.on?.(\"error\", () => { consoleGone = true; });\n }\n}\nexport function consoleClosed(): boolean {\n return consoleGone;\n}\n\nexport function log(level: \"info\" | \"warn\" | \"error\", msg: string, extra?: unknown): void {\n const line = `[${new Date().toISOString()}] [${level}] ${msg}${extra !== undefined ? \" \" + safeJson(extra) : \"\"}`;\n try {\n const d = new Date();\n const name = fileName(d);\n if (name !== today && logDir) {\n today = name;\n logFile = join(logDir, name);\n }\n if (logFile) appendFileSync(logFile, line + \"\\n\", \"utf8\");\n } catch {}\n guardConsole();\n if (consoleGone) return;\n const stream = level === \"info\" ? process.stdout : process.stderr;\n if (stream?.destroyed || stream?.writableEnded) { consoleGone = true; return; }\n const fn = level === \"error\" ? console.error : level === \"warn\" ? console.warn : console.log;\n try {\n fn(`[agent-console] ${msg}`, extra !== undefined ? extra : \"\");\n } catch {\n consoleGone = true;\n }\n}\n\nfunction safeJson(v: unknown): string {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n","// Host / Origin / token checks (timingSafeEqual).\n//\n// Security model (after the PR #535 review):\n// - Host is checked on every HTTP request and WS upgrade and must be 127.0.0.1: or localhost:,\n// to block DNS rebinding (requests from a rebound page carry no Origin, so only Host identifies them).\n// - Origin: null (opaque origin) is not trusted. Any website can send Origin: null from a sandboxed iframe, a data: or a file: page,\n// so null by itself means nothing. The token is the only authorization:\n// * token routes (/api/*, /attachments/*, WS hello) let a null origin \"present\" the token,\n// because Magpie's plugin page is a sandbox=\"allow-scripts\" iframe and can only request as null;\n// * static routes (/, app.js etc.) always 403 for null and send no CORS headers.\n// - Any other website's Origin is refused, even with the correct token.\nimport { timingSafeEqual, createHash } from \"node:crypto\";\n\nexport type CheckResult = { ok: true } | { ok: false; code: number; message: string };\n\n// none: no Origin (ordinary navigation, `;\n const head = /]*)?>/i.exec(html);\n if (head) return html.slice(0, head.index + head[0].length) + tag + html.slice(head.index + head[0].length);\n const root = /]*)?>/i.exec(html);\n if (root) return html.slice(0, root.index + root[0].length) + tag + html.slice(root.index + root[0].length);\n const doctype = /^\\s*]*>/i.exec(html);\n if (doctype) return html.slice(0, doctype[0].length) + tag + html.slice(doctype[0].length);\n return tag + html;\n}\n","// Preview proxy (1.2): a local-only reverse proxy, one 127.0.0.1: listener per loopback target origin.\n//\n// Why: Magpie's page frame is sandbox=\"allow-scripts\" and the sandbox is inherited by every child frame, so a plain\n//