MCPcopy Create free account
hub / github.com/UsefulSoftwareCo/executor / serveReplayBrain

Function serveReplayBrain

e2e/src/clients/replay-brain.ts:93–208  ·  view source on GitHub ↗
(
  respond: (ctx: BrainContext) => BrainResponse,
)

Source from the content-addressed store, hash-verified

91 * `respond` is called once per chat-completions request.
92 */
93export const serveReplayBrain = (
94 respond: (ctx: BrainContext) => BrainResponse,
95): Effect.Effect<ReplayBrain, never, Scope.Scope> =>
96 Effect.acquireRelease(
97 Effect.callback<{ server: Server; brain: ReplayBrain }>((resume) => {
98 const served: BrainRequest[] = [];
99 const errors: string[] = [];
100
101 const server = createServer((request, response) => {
102 if (!request.url?.includes("/chat/completions")) {
103 response.writeHead(404).end();
104 return;
105 }
106 let raw = "";
107 request.on("data", (piece: Buffer) => (raw += piece.toString("utf8")));
108 request.on("end", () => {
109 const body = JSON.parse(raw || "{}") as WireBody;
110 const messages = (body.messages ?? []).map((message) => ({
111 role: message.role,
112 content: contentText(message.content),
113 }));
114 const toolNames = (body.tools ?? [])
115 .map((tool) => tool.function?.name ?? "")
116 .filter(Boolean);
117 const requestIndex = served.length;
118 served.push({ messages, toolNames });
119
120 const lastOf = (role: string) =>
121 [...messages].reverse().find((message) => message.role === role)?.content;
122
123 let scripted: BrainResponse;
124 // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: a throwing script must surface as a recorded error + a stop response, not a hung agent
125 try {
126 scripted = respond({
127 requestIndex,
128 lastRole: messages.at(-1)?.role ?? "",
129 lastUser: lastOf("user") ?? "",
130 lastToolResult: lastOf("tool"),
131 toolNames,
132 });
133 } catch (error) {
134 errors.push(`respond() threw on request ${requestIndex}: ${String(error)}`);
135 scripted = { text: "(replay brain script error)" };
136 }
137
138 // Resolve a scripted tool name against the agent's namespaced names.
139 let resolvedTool: { name: string; args: unknown } | undefined;
140 if (scripted.tool) {
141 const wanted = scripted.tool.name;
142 const match =
143 toolNames.find((name) => name === wanted) ??
144 toolNames.find((name) => name.endsWith(wanted));
145 if (match) {
146 resolvedTool = { name: match, args: scripted.tool.args };
147 } else {
148 errors.push(
149 `request ${requestIndex}: no offered tool matches "${wanted}" (offered: ${toolNames.join(", ")})`,
150 );

Callers

nothing calls this directly

Calls 12

contentTextFunction · 0.85
lastOfFunction · 0.85
sseChunkFunction · 0.85
resumeFunction · 0.85
endMethod · 0.80
toStringMethod · 0.80
pushMethod · 0.80
listenMethod · 0.80
addressMethod · 0.80
syncMethod · 0.65
closeMethod · 0.65
respondFunction · 0.50

Tested by

no test coverage detected