feat: stream reasoning_content and segment agent messages
build-and-push / build (push) Successful in 6m36s
build-and-push / build (push) Successful in 6m36s
Forward ACP agent_thought_chunk as OpenAI-style reasoning_content, and insert --- separators between distinct agent_message runs in one completion.
This commit is contained in:
+25
-2
@@ -38,7 +38,13 @@ import {
|
|||||||
toolNudgeBlock,
|
toolNudgeBlock,
|
||||||
noToolsDirectiveBlock,
|
noToolsDirectiveBlock,
|
||||||
} from "./message-converter.mjs";
|
} from "./message-converter.mjs";
|
||||||
import { textChunk, toolCallChunk, finishChunk, nonStreamResponse } from "./stream-translator.mjs";
|
import {
|
||||||
|
textChunk,
|
||||||
|
reasoningChunk,
|
||||||
|
toolCallChunk,
|
||||||
|
finishChunk,
|
||||||
|
nonStreamResponse,
|
||||||
|
} from "./stream-translator.mjs";
|
||||||
|
|
||||||
const PORT = parseInt(process.env.PORT || "4646", 10);
|
const PORT = parseInt(process.env.PORT || "4646", 10);
|
||||||
const EDGE_PORT = parseInt(process.env.EDGE_PORT || "4647", 10);
|
const EDGE_PORT = parseInt(process.env.EDGE_PORT || "4647", 10);
|
||||||
@@ -348,6 +354,7 @@ async function streamSessionTurn({
|
|||||||
id: requestId,
|
id: requestId,
|
||||||
model: session.detectedModel || "auto",
|
model: session.detectedModel || "auto",
|
||||||
text: result.text,
|
text: result.text,
|
||||||
|
reasoning: result.reasoning,
|
||||||
toolCalls: result.calls,
|
toolCalls: result.calls,
|
||||||
finishReason: result.finishReason,
|
finishReason: result.finishReason,
|
||||||
usage: result.usage,
|
usage: result.usage,
|
||||||
@@ -420,6 +427,18 @@ async function streamSessionTurn({
|
|||||||
isFirst = false;
|
isFirst = false;
|
||||||
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
|
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
|
||||||
},
|
},
|
||||||
|
onReasoningDelta: (delta) => {
|
||||||
|
if (res.writableEnded || finished) return;
|
||||||
|
markFirstToken("reasoning");
|
||||||
|
const chunk = reasoningChunk({
|
||||||
|
id: requestId,
|
||||||
|
model: session.detectedModel || "auto",
|
||||||
|
delta,
|
||||||
|
isFirst,
|
||||||
|
});
|
||||||
|
isFirst = false;
|
||||||
|
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
|
||||||
|
},
|
||||||
onToolCall: (call) => {
|
onToolCall: (call) => {
|
||||||
if (res.writableEnded || finished) return;
|
if (res.writableEnded || finished) return;
|
||||||
sawToolCall = true;
|
sawToolCall = true;
|
||||||
@@ -479,6 +498,7 @@ async function streamSessionTurn({
|
|||||||
function collectSessionTurn(session, blocks) {
|
function collectSessionTurn(session, blocks) {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
let text = "";
|
let text = "";
|
||||||
|
let reasoning = "";
|
||||||
const calls = [];
|
const calls = [];
|
||||||
let finishReason = "stop";
|
let finishReason = "stop";
|
||||||
let usage = null;
|
let usage = null;
|
||||||
@@ -486,13 +506,16 @@ function collectSessionTurn(session, blocks) {
|
|||||||
onAssistantDelta: (d) => {
|
onAssistantDelta: (d) => {
|
||||||
text += d;
|
text += d;
|
||||||
},
|
},
|
||||||
|
onReasoningDelta: (d) => {
|
||||||
|
reasoning += d;
|
||||||
|
},
|
||||||
onToolCall: (c) => {
|
onToolCall: (c) => {
|
||||||
calls.push(c);
|
calls.push(c);
|
||||||
},
|
},
|
||||||
onFinish: (reason, u) => {
|
onFinish: (reason, u) => {
|
||||||
finishReason = reason;
|
finishReason = reason;
|
||||||
usage = u;
|
usage = u;
|
||||||
resolve({ text, calls, finishReason, usage });
|
resolve({ text, reasoning, calls, finishReason, usage });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+29
-1
@@ -32,6 +32,8 @@ export const MAX_CONCURRENT_SESSIONS = parseInt(process.env.PROXY_MAX_CONCURRENT
|
|||||||
export const TOOL_CALL_BATCH_MS = parseInt(process.env.PROXY_TOOL_CALL_BATCH_MS || "50", 10);
|
export const TOOL_CALL_BATCH_MS = parseInt(process.env.PROXY_TOOL_CALL_BATCH_MS || "50", 10);
|
||||||
/** Number of pre-bootstrapped ACP processes kept ready (0 disables). */
|
/** Number of pre-bootstrapped ACP processes kept ready (0 disables). */
|
||||||
export const WARM_POOL_SIZE = parseInt(process.env.PROXY_WARM_POOL_SIZE || "2", 10);
|
export const WARM_POOL_SIZE = parseInt(process.env.PROXY_WARM_POOL_SIZE || "2", 10);
|
||||||
|
/** Inserted between distinct agent_message segments in one OpenAI completion. */
|
||||||
|
export const MESSAGE_SEGMENT_SEPARATOR = "\n\n---\n\n";
|
||||||
const REAL_AGENT = process.env.CURSOR_AGENT_BIN || "/usr/local/bin/agent.real";
|
const REAL_AGENT = process.env.CURSOR_AGENT_BIN || "/usr/local/bin/agent.real";
|
||||||
const MCP_BRIDGE = process.env.MCP_BRIDGE_BIN || "/app/scripts/mcp-stdio-bridge.sh";
|
const MCP_BRIDGE = process.env.MCP_BRIDGE_BIN || "/app/scripts/mcp-stdio-bridge.sh";
|
||||||
|
|
||||||
@@ -263,6 +265,10 @@ export class CursorSession {
|
|||||||
this._handlers = null;
|
this._handlers = null;
|
||||||
this._hasToolCallInTurn = false;
|
this._hasToolCallInTurn = false;
|
||||||
this._promptInFlight = false;
|
this._promptInFlight = false;
|
||||||
|
/** Last ACP stream kind in this turn: "message" | "thought" | "other" | null. */
|
||||||
|
this._lastStreamKind = null;
|
||||||
|
/** Whether any assistant content (not reasoning) was emitted this turn. */
|
||||||
|
this._emittedAssistantText = false;
|
||||||
this.bootstrapped = false;
|
this.bootstrapped = false;
|
||||||
this.fromWarmPool = false;
|
this.fromWarmPool = false;
|
||||||
/** Last start-stage timings (ms), for request logs. */
|
/** Last start-stage timings (ms), for request logs. */
|
||||||
@@ -514,13 +520,33 @@ export class CursorSession {
|
|||||||
if (update.sessionUpdate === "agent_message_chunk") {
|
if (update.sessionUpdate === "agent_message_chunk") {
|
||||||
const content = update.content;
|
const content = update.content;
|
||||||
if (content?.type === "text" && content.text) {
|
if (content?.type === "text" && content.text) {
|
||||||
|
// Distinct agent_message runs (interrupted by thought/other) become
|
||||||
|
// separate segments in one OpenAI completion, joined by a separator.
|
||||||
|
if (this._lastStreamKind !== "message" && this._emittedAssistantText) {
|
||||||
|
this._handlers.onAssistantDelta(MESSAGE_SEGMENT_SEPARATOR);
|
||||||
|
}
|
||||||
this._handlers.onAssistantDelta(content.text);
|
this._handlers.onAssistantDelta(content.text);
|
||||||
|
this._emittedAssistantText = true;
|
||||||
|
this._lastStreamKind = "message";
|
||||||
}
|
}
|
||||||
this._touchTimer();
|
this._touchTimer();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// agent_thought_chunk and other updates are ignored for OpenAI output.
|
if (update.sessionUpdate === "agent_thought_chunk") {
|
||||||
|
const content = update.content;
|
||||||
|
if (content?.type === "text" && content.text) {
|
||||||
|
if (typeof this._handlers.onReasoningDelta === "function") {
|
||||||
|
this._handlers.onReasoningDelta(content.text);
|
||||||
|
}
|
||||||
|
this._lastStreamKind = "thought";
|
||||||
|
}
|
||||||
|
this._touchTimer();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// tool_call / plan / etc. break message-segment continuity.
|
||||||
|
this._lastStreamKind = "other";
|
||||||
this._touchTimer();
|
this._touchTimer();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -530,6 +556,8 @@ export class CursorSession {
|
|||||||
runTurn(blocks, handlers) {
|
runTurn(blocks, handlers) {
|
||||||
this._handlers = handlers;
|
this._handlers = handlers;
|
||||||
this.lastActivityAt = Date.now();
|
this.lastActivityAt = Date.now();
|
||||||
|
this._lastStreamKind = null;
|
||||||
|
this._emittedAssistantText = false;
|
||||||
|
|
||||||
if (blocks === null) {
|
if (blocks === null) {
|
||||||
// Follow-up after tool_calls: same session/prompt is still in flight.
|
// Follow-up after tool_calls: same session/prompt is still in flight.
|
||||||
|
|||||||
@@ -1,12 +1,85 @@
|
|||||||
import { describe, it } from "node:test";
|
import { describe, it } from "node:test";
|
||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import {
|
import {
|
||||||
|
CursorSession,
|
||||||
extractToolNameFromPermission,
|
extractToolNameFromPermission,
|
||||||
fmtMs,
|
fmtMs,
|
||||||
nowMs,
|
nowMs,
|
||||||
|
MESSAGE_SEGMENT_SEPARATOR,
|
||||||
WARM_POOL_SIZE,
|
WARM_POOL_SIZE,
|
||||||
} from "./session-manager.mjs";
|
} from "./session-manager.mjs";
|
||||||
|
|
||||||
|
function collectUpdates(session) {
|
||||||
|
const assistant = [];
|
||||||
|
const reasoning = [];
|
||||||
|
session._handlers = {
|
||||||
|
onAssistantDelta: (d) => assistant.push(d),
|
||||||
|
onReasoningDelta: (d) => reasoning.push(d),
|
||||||
|
};
|
||||||
|
session.acpSessionId = "acp-1";
|
||||||
|
session._touchTimer = () => {};
|
||||||
|
return { assistant, reasoning };
|
||||||
|
}
|
||||||
|
|
||||||
|
function update(sessionUpdate, text) {
|
||||||
|
return {
|
||||||
|
sessionId: "acp-1",
|
||||||
|
update: {
|
||||||
|
sessionUpdate,
|
||||||
|
content: { type: "text", text },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("agent_message separators + agent_thought reasoning", () => {
|
||||||
|
it("exports the segment separator", () => {
|
||||||
|
assert.equal(MESSAGE_SEGMENT_SEPARATOR, "\n\n---\n\n");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not separate contiguous agent_message chunks", () => {
|
||||||
|
const session = new CursorSession({ sessionId: "s1", tools: [], model: "auto" });
|
||||||
|
const { assistant, reasoning } = collectUpdates(session);
|
||||||
|
session._onSessionUpdate(update("agent_message_chunk", "Hello"));
|
||||||
|
session._onSessionUpdate(update("agent_message_chunk", " world"));
|
||||||
|
assert.deepEqual(assistant, ["Hello", " world"]);
|
||||||
|
assert.deepEqual(reasoning, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("inserts separator after thought between message segments", () => {
|
||||||
|
const session = new CursorSession({ sessionId: "s1", tools: [], model: "auto" });
|
||||||
|
const { assistant, reasoning } = collectUpdates(session);
|
||||||
|
session._onSessionUpdate(update("agent_message_chunk", "First"));
|
||||||
|
session._onSessionUpdate(update("agent_thought_chunk", "ponder"));
|
||||||
|
session._onSessionUpdate(update("agent_message_chunk", "Second"));
|
||||||
|
assert.deepEqual(assistant, ["First", MESSAGE_SEGMENT_SEPARATOR, "Second"]);
|
||||||
|
assert.deepEqual(reasoning, ["ponder"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("inserts separator after non-message updates", () => {
|
||||||
|
const session = new CursorSession({ sessionId: "s1", tools: [], model: "auto" });
|
||||||
|
const { assistant } = collectUpdates(session);
|
||||||
|
session._onSessionUpdate(update("agent_message_chunk", "A"));
|
||||||
|
session._onSessionUpdate({
|
||||||
|
sessionId: "acp-1",
|
||||||
|
update: { sessionUpdate: "tool_call", toolCallId: "t1" },
|
||||||
|
});
|
||||||
|
session._onSessionUpdate(update("agent_message_chunk", "B"));
|
||||||
|
assert.deepEqual(assistant, ["A", MESSAGE_SEGMENT_SEPARATOR, "B"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resets segment state on runTurn", () => {
|
||||||
|
const session = new CursorSession({ sessionId: "s1", tools: [], model: "auto" });
|
||||||
|
const { assistant } = collectUpdates(session);
|
||||||
|
session._onSessionUpdate(update("agent_message_chunk", "Old"));
|
||||||
|
// Fake acp so runTurn follow-up path does not throw.
|
||||||
|
session.acp = { request: async () => ({ stopReason: "end_turn" }) };
|
||||||
|
session.runTurn(null, session._handlers);
|
||||||
|
assistant.length = 0;
|
||||||
|
session._onSessionUpdate(update("agent_message_chunk", "New"));
|
||||||
|
assert.deepEqual(assistant, ["New"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("fmtMs / nowMs", () => {
|
describe("fmtMs / nowMs", () => {
|
||||||
it("formats durations to one decimal millisecond", () => {
|
it("formats durations to one decimal millisecond", () => {
|
||||||
assert.equal(fmtMs(12.34), "12.3ms");
|
assert.equal(fmtMs(12.34), "12.3ms");
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
/**
|
/**
|
||||||
* Build a streaming chunk carrying an assistant text delta.
|
* Build a streaming chunk carrying an assistant text delta.
|
||||||
*/
|
*/
|
||||||
export function textChunk({ id, model, delta, isFirst }) {
|
function baseChunk(id, model, delta) {
|
||||||
return {
|
return {
|
||||||
id: `chatcmpl-${id}`,
|
id: `chatcmpl-${id}`,
|
||||||
object: "chat.completion.chunk",
|
object: "chat.completion.chunk",
|
||||||
@@ -17,13 +17,26 @@ export function textChunk({ id, model, delta, isFirst }) {
|
|||||||
choices: [
|
choices: [
|
||||||
{
|
{
|
||||||
index: 0,
|
index: 0,
|
||||||
delta: { ...(isFirst ? { role: "assistant" } : {}), content: delta },
|
delta,
|
||||||
finish_reason: null,
|
finish_reason: null,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function textChunk({ id, model, delta, isFirst }) {
|
||||||
|
const deltaObj = isFirst ? { role: "assistant", content: delta } : { content: delta };
|
||||||
|
return baseChunk(id, model, deltaObj);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** o-series / DeepSeek-style reasoning stream chunk from ACP agent_thought_chunk. */
|
||||||
|
export function reasoningChunk({ id, model, delta, isFirst }) {
|
||||||
|
const deltaObj = isFirst
|
||||||
|
? { role: "assistant", reasoning_content: delta }
|
||||||
|
: { reasoning_content: delta };
|
||||||
|
return baseChunk(id, model, deltaObj);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build a streaming chunk carrying an OpenAI tool_calls delta. The client
|
* Build a streaming chunk carrying an OpenAI tool_calls delta. The client
|
||||||
* receives this when cursor-agent decides to call an MCP tool.
|
* receives this when cursor-agent decides to call an MCP tool.
|
||||||
@@ -80,7 +93,7 @@ export function errorChunk({ id, model, message }) {
|
|||||||
/**
|
/**
|
||||||
* Build a non-streaming chat.completion response. Used when stream=false.
|
* Build a non-streaming chat.completion response. Used when stream=false.
|
||||||
*/
|
*/
|
||||||
export function nonStreamResponse({ id, model, text, toolCalls, finishReason, usage }) {
|
export function nonStreamResponse({ id, model, text, reasoning, toolCalls, finishReason, usage }) {
|
||||||
const message =
|
const message =
|
||||||
toolCalls && toolCalls.length > 0
|
toolCalls && toolCalls.length > 0
|
||||||
? {
|
? {
|
||||||
@@ -93,6 +106,9 @@ export function nonStreamResponse({ id, model, text, toolCalls, finishReason, us
|
|||||||
})),
|
})),
|
||||||
}
|
}
|
||||||
: { role: "assistant", content: text || "" };
|
: { role: "assistant", content: text || "" };
|
||||||
|
if (reasoning) {
|
||||||
|
message.reasoning_content = reasoning;
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
id: `chatcmpl-${id}`,
|
id: `chatcmpl-${id}`,
|
||||||
object: "chat.completion",
|
object: "chat.completion",
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { describe, it } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import {
|
||||||
|
textChunk,
|
||||||
|
reasoningChunk,
|
||||||
|
nonStreamResponse,
|
||||||
|
} from "./stream-translator.mjs";
|
||||||
|
|
||||||
|
describe("reasoningChunk", () => {
|
||||||
|
it("puts role + reasoning_content on the first chunk", () => {
|
||||||
|
const chunk = reasoningChunk({
|
||||||
|
id: "abc",
|
||||||
|
model: "auto",
|
||||||
|
delta: "think",
|
||||||
|
isFirst: true,
|
||||||
|
});
|
||||||
|
assert.equal(chunk.object, "chat.completion.chunk");
|
||||||
|
assert.deepEqual(chunk.choices[0].delta, {
|
||||||
|
role: "assistant",
|
||||||
|
reasoning_content: "think",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("omits role on subsequent reasoning chunks", () => {
|
||||||
|
const chunk = reasoningChunk({
|
||||||
|
id: "abc",
|
||||||
|
model: "auto",
|
||||||
|
delta: " more",
|
||||||
|
isFirst: false,
|
||||||
|
});
|
||||||
|
assert.deepEqual(chunk.choices[0].delta, { reasoning_content: " more" });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("textChunk", () => {
|
||||||
|
it("still emits content deltas", () => {
|
||||||
|
const chunk = textChunk({
|
||||||
|
id: "abc",
|
||||||
|
model: "auto",
|
||||||
|
delta: "hi",
|
||||||
|
isFirst: false,
|
||||||
|
});
|
||||||
|
assert.deepEqual(chunk.choices[0].delta, { content: "hi" });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("nonStreamResponse", () => {
|
||||||
|
it("includes reasoning_content when provided", () => {
|
||||||
|
const resp = nonStreamResponse({
|
||||||
|
id: "abc",
|
||||||
|
model: "auto",
|
||||||
|
text: "answer",
|
||||||
|
reasoning: "chain",
|
||||||
|
toolCalls: [],
|
||||||
|
finishReason: "stop",
|
||||||
|
});
|
||||||
|
assert.equal(resp.choices[0].message.content, "answer");
|
||||||
|
assert.equal(resp.choices[0].message.reasoning_content, "chain");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("omits reasoning_content when empty/absent", () => {
|
||||||
|
const resp = nonStreamResponse({
|
||||||
|
id: "abc",
|
||||||
|
model: "auto",
|
||||||
|
text: "answer",
|
||||||
|
finishReason: "stop",
|
||||||
|
});
|
||||||
|
assert.equal("reasoning_content" in resp.choices[0].message, false);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user