@juspay/neurolink
Version:
The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002
375 lines (374 loc) • 14 kB
JavaScript
/**
* Hidden key on a StreamResult's metadata under which a provider stream path
* records RunCoreStreamDetails. Non-enumerable and symbol-keyed, so existing
* stream() readers, spreads and JSON never see it.
*/
export const RUN_CORE_STREAM_DETAILS = Symbol.for("neurolink.runCore.streamDetails");
/*
* Which providers the collect path covers is data, not a list here: a
* provider qualifies when its descriptor declares `wire: "openai-chat"`, i.e.
* it runs on the shared Chat Completions base, whose stream path resolves
* structured output, tool calls, usage and the finish reason itself and
* records the step details collect needs (RUN_CORE_STREAM_DETAILS). The
* caller passes that lookup in (RunCoreWireLookup), so this module stays free
* of the factory.
*/
/**
* The generate options the collect path handles the same way generate does.
* A request carrying any other key keeps today's path, so a feature the
* stream path treats differently (evaluation, workflows, media output,
* conversation memory, orchestration, per-request middleware) is never
* silently changed.
*
* `schema` is not here yet: the generate path retries a provider that
* rejects `response_format` and replaces the content with the recovered JSON
* after a re-ask, and the stream path does neither. Nor is `timeout`: the
* generate path caps each model call at three times it, while the stream
* path only re-arms its idle timer per chunk.
*/
const RUN_CORE_OPTION_KEYS = new Set([
"input",
"provider",
"model",
"systemPrompt",
"temperature",
"maxTokens",
"topP",
"topK",
"stopSequences",
"tools",
"disableTools",
"toolChoice",
"maxSteps",
"credentials",
"context",
"disableInternalFallback",
"requestId",
]);
/** True when the switch is on for this instance or the environment. */
export function isRunCoreEnabled(instanceFlag) {
if (instanceFlag !== undefined) {
return instanceFlag;
}
const env = process.env.NEUROLINK_RUN_CORE?.trim().toLowerCase();
return env === "1" || env === "true";
}
/**
* Whether a generate request can be answered by collecting `run()` events.
* Text-only input, a provider on the openai-chat wire, and only option keys the
* collect path covers.
*/
export function runCoreSupports(options, wireOf) {
// A provider given as a callback is resolved later in generate(); until
// then it names nothing to look up, so the request keeps today's path.
if (typeof options.provider !== "string" ||
wireOf(options.provider) !== "openai-chat") {
return false;
}
for (const key of Object.keys(options)) {
const value = options[key];
if (value !== undefined && !RUN_CORE_OPTION_KEYS.has(key)) {
return false;
}
}
const input = options.input;
if (!input || typeof input.text !== "string") {
return false;
}
for (const key of Object.keys(input)) {
if (key !== "text" && input[key] !== undefined) {
return false;
}
}
return true;
}
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
/**
* The run's token usage: the StreamResult's own field when a wrapper set one,
* else the analytics the provider settles once the stream has drained, plus
* the tokens a structured-output re-ask spent (the generate path counts them
* in its usage too).
*/
async function settledUsage(result, metadata) {
let usage = result.usage;
if (!usage) {
const analytics = await Promise.resolve(result.analytics).catch(() => undefined);
usage = analytics?.tokenUsage;
}
const reask = metadata?.structuredDataUsage;
if (!usage || !isRecord(reask)) {
return usage;
}
const extraInput = typeof reask.inputTokens === "number" ? reask.inputTokens : 0;
const extraOutput = typeof reask.outputTokens === "number" ? reask.outputTokens : 0;
if (extraInput === 0 && extraOutput === 0) {
return usage;
}
return {
...usage,
input: usage.input + extraInput,
output: usage.output + extraOutput,
total: usage.total + extraInput + extraOutput,
};
}
/** The details a provider stream path recorded for run(), if any. */
function streamDetails(metadata) {
const value = metadata
? Reflect.get(metadata, RUN_CORE_STREAM_DETAILS)
: undefined;
if (isRecord(value) &&
typeof value.stepsUsed === "number" &&
typeof value.stopReason === "string" &&
Array.isArray(value.toolCallIds) &&
Array.isArray(value.toolStartTimes) &&
typeof value.finalStepText === "string") {
return value;
}
return undefined;
}
/** The text and reasoning events one stream chunk carries. */
function* chunkEvents(part) {
if (!isRecord(part)) {
return;
}
if (typeof part.reasoning === "string" && part.reasoning.length > 0) {
yield { type: "reasoning", delta: part.reasoning };
}
// Audio and image chunks carry no text; the text kind ignores them.
if (part.type !== "audio" &&
part.type !== "tts_audio" &&
part.type !== "image" &&
typeof part.content === "string" &&
part.content.length > 0) {
yield { type: "text", delta: part.content };
}
}
/**
* Tool calls and their results, both taken from ONE record set so a result is
* never paired with another attempt's call. A result whose `toolCalls` is set
* (another provider, or the cross-provider fallback, which rebinds it) uses
* that list with its `toolResults`; otherwise the executions this provider
* recorded, with the call ids from its stream details.
*/
function* toolEvents(result, details) {
const reported = result.toolCalls ?? [];
if (reported.length > 0) {
const results = result.toolResults ?? [];
for (const [index, call] of reported.entries()) {
const toolCallId = call.toolCallId ?? call.id;
yield {
type: "tool-call",
...(toolCallId ? { toolCallId } : {}),
toolName: call.toolName,
args: (call.args ?? call.parameters ?? {}),
};
const match = results.find((r) => toolCallId !== undefined && r.id === toolCallId) ??
results[index];
if (match) {
yield {
type: "tool-result",
...(toolCallId ? { toolCallId } : {}),
toolName: match.toolName,
output: match.output,
...(typeof match.executionTime === "number"
? { durationMs: match.executionTime }
: {}),
};
}
}
return;
}
// Typed as ToolExecutionSummary[], but this stream path's live getter
// returns {name, input, output, duration}, so the fields are read by guard.
const executions = (result.toolExecutions ?? []).filter(isRecord);
for (const [index, execution] of executions.entries()) {
const toolCallId = details?.toolCallIds[index] || undefined;
const startedAt = details?.toolStartTimes[index];
const toolName = String(execution.name ?? execution.toolName ?? "");
yield {
type: "tool-call",
...(toolCallId ? { toolCallId } : {}),
toolName,
args: (isRecord(execution.input) ? execution.input : {}),
};
yield {
type: "tool-result",
...(toolCallId ? { toolCallId } : {}),
toolName,
output: execution.output,
...(typeof execution.duration === "number"
? { durationMs: execution.duration }
: {}),
...(typeof startedAt === "number" ? { startedAt } : {}),
};
}
}
/**
* Turn today's StreamResult into run events: start, the text and reasoning
* deltas in order, then (once the stream has drained) the tool calls and
* results, the object for a schema turn, usage and finish. A stream that
* throws ends with an error event.
*
* The stream is pulled once before `start` is yielded, so a caller that stops
* at any event (even the first) closes a started stream, whose own cleanup
* then runs. Tool events come after the text because this stream path reports
* tool executions on the result, not inline; a later step moves them inline.
*/
export async function* streamResultToRunEvents(result, requestId) {
const iterator = result.stream[Symbol.asyncIterator]();
let drained = false;
try {
let next;
try {
next = await iterator.next();
}
catch (error) {
drained = true;
yield errorEvent(error);
return;
}
yield {
type: "start",
provider: result.provider ?? "",
model: result.model ?? "",
requestId,
};
try {
while (!next.done) {
yield* chunkEvents(next.value);
next = await iterator.next();
}
drained = true;
}
catch (error) {
drained = true;
yield errorEvent(error);
return;
}
}
finally {
if (!drained) {
await iterator.return?.(undefined);
}
}
const metadata = result.metadata;
const details = streamDetails(metadata);
yield* toolEvents(result, details);
if (metadata && metadata.structuredData !== undefined) {
yield { type: "object", value: metadata.structuredData };
}
const usage = await settledUsage(result, metadata);
if (usage) {
yield { type: "usage", usage };
}
const reason = (typeof metadata?.finishReason === "string"
? metadata.finishReason
: undefined) ??
result.finishReason ??
"stop";
const rawReason = (typeof metadata?.rawFinishReason === "string"
? metadata.rawFinishReason
: undefined) ?? result.rawFinishReason;
const stopReason = details?.stopReason ??
(metadata?.stopReason ?? result.stopReason);
const stepsUsed = details?.stepsUsed ??
(typeof metadata?.stepsUsed === "number" ? metadata.stepsUsed : undefined);
yield {
type: "finish",
reason,
...(rawReason !== undefined ? { rawReason } : {}),
...(stopReason !== undefined ? { stopReason } : {}),
...(stepsUsed !== undefined ? { stepsUsed } : {}),
// Only a multi-step turn's answer differs from the joined text deltas.
...(details && details.stepsUsed > 1
? { answerText: details.finalStepText }
: {}),
};
}
function errorEvent(error) {
return {
type: "error",
message: error instanceof Error ? error.message : String(error),
error,
};
}
/**
* Collect a run's events. An error event is rethrown as the error it carries,
* so a caller of generate() sees the same failure the stream raised. The
* content is the joined text, or a multi-step turn's answer text, which is
* what generate() returns; reasoning accumulates across steps, as there.
*/
export async function collectRunEvents(events) {
const collected = {
content: "",
hasObject: false,
reasoning: "",
toolCalls: [],
toolResults: [],
toolExecutions: [],
toolsUsed: [],
};
for await (const event of events) {
switch (event.type) {
case "start":
collected.provider = event.provider || undefined;
collected.model = event.model || undefined;
break;
case "text":
collected.content += event.delta;
break;
case "reasoning":
collected.reasoning += event.delta;
break;
case "tool-call":
collected.toolCalls.push({
toolCallId: event.toolCallId ?? "",
toolName: event.toolName,
args: event.args,
});
break;
case "tool-result": {
collected.toolResults.push(event.output);
// The most recent call with this id: a server can reuse an id across
// steps, and each call is emitted directly before its result.
const call = [...collected.toolCalls]
.reverse()
.find((c) => event.toolCallId !== undefined &&
c.toolCallId === event.toolCallId);
collected.toolExecutions.push({
name: event.toolName,
input: call?.args ?? {},
output: event.output,
duration: event.durationMs ?? 0,
...(event.startedAt !== undefined
? { startedAt: event.startedAt }
: {}),
});
// One entry per executed tool, as the generate path reports it.
collected.toolsUsed.push(event.toolName);
break;
}
case "object":
collected.structuredData = event.value;
collected.hasObject = true;
break;
case "usage":
collected.usage = event.usage;
break;
case "finish":
collected.finishReason = event.reason;
collected.rawFinishReason = event.rawReason;
collected.stopReason = event.stopReason;
collected.stepsUsed = event.stepsUsed;
if (event.answerText !== undefined) {
collected.content = event.answerText;
}
break;
case "error":
throw event.error;
}
}
return collected;
}