@openai/agents-core
Version:
The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows.
230 lines • 7.86 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveMemoryRolloutId = resolveMemoryRolloutId;
exports.buildMemoryRolloutPayload = buildMemoryRolloutPayload;
exports.validateRolloutId = validateRolloutId;
exports.normalizeRolloutSlug = normalizeRolloutSlug;
exports.renderPhaseOnePrompt = renderPhaseOnePrompt;
const errors_1 = require("../../errors.js");
const items_1 = require("../../runner/items.js");
const stableJson_1 = require("../shared/stableJson.js");
const EXCLUDED_MEMORY_ITEM_TYPES = new Set([
'compaction',
'image_generation_call',
'reasoning',
]);
const INCLUDED_MEMORY_ITEM_TYPES = new Set([
'apply_patch_call',
'apply_patch_call_output',
'computer_call',
'computer_call_output',
'custom_tool_call',
'custom_tool_call_output',
'function_call',
'function_call_output',
'function_call_result',
'hosted_tool_call',
'local_shell_call',
'local_shell_call_output',
'mcp_approval_request',
'mcp_approval_response',
'mcp_call',
'program',
'program_output',
'shell_call',
'shell_call_output',
'tool_search_call',
'tool_search_output',
'web_search_call',
]);
function resolveMemoryRolloutId(identity) {
return validateRolloutId(identity.conversationId ??
identity.sdkSessionId ??
identity.groupId ??
identity.fallbackId);
}
function buildMemoryRolloutPayload(state, args) {
const finalOutput = finalOutputForMemory(state);
const interruptions = interruptionsForMemory(state).map((item) => sanitizeForMemoryJson(item.rawItem));
const payload = {
updated_at: utcIsoTimestamp(),
rollout_id: args.rolloutId,
input: sanitizeForMemoryJson(sanitizeMemoryItems((0, items_1.toAgentInputList)(args.inputOverride ?? state._originalInput))),
generated_items: sanitizeForMemoryJson(sanitizeMemoryItems((0, items_1.extractOutputItemsFromRunItems)(state._generatedItems, state._reasoningItemIdPolicy))),
terminal_metadata: terminalMetadataForMemory(state, args.exception, finalOutput),
};
if (interruptions.length > 0) {
payload.interruptions = interruptions;
}
if (finalOutput !== null) {
payload.final_output = sanitizeForMemoryJson(finalOutput);
}
return payload;
}
function validateRolloutId(value) {
const normalized = value.trim();
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(normalized)) {
throw new Error("Sandbox memory rollout ID must be a file-safe ID containing only letters, numbers, '.', '_', or '-'.");
}
return normalized;
}
function normalizeRolloutSlug(value) {
const slug = value.trim().endsWith('.md')
? value.trim().slice(0, -3)
: value.trim();
if (!/^[a-z0-9][a-z0-9_-]{0,79}$/.test(slug)) {
throw new Error(`Invalid rollout_slug: ${value}`);
}
return slug;
}
function renderPhaseOnePrompt(rolloutContents) {
const payloads = rolloutContents
.split('\n')
.filter((line) => line.trim().length > 0)
.map((line) => JSON.parse(line));
if (payloads.length === 0) {
throw new Error('rollout_contents must contain at least one JSONL record');
}
const lastPayload = payloads[payloads.length - 1];
const terminalMetadata = payloads.length === 1
? (lastPayload.terminal_metadata ?? {})
: {
segment_count: payloads.length,
final_terminal_metadata: lastPayload.terminal_metadata ?? {},
terminal_states: payloads.map((payload) => {
const terminal = payload.terminal_metadata;
return terminal && typeof terminal === 'object'
? (terminal.terminal_state ??
'unknown')
: 'unknown';
}),
};
return stringifySortedJson(terminalMetadata);
}
function sanitizeMemoryItems(items) {
return items.filter((item) => shouldIncludeMemoryItem(item));
}
function shouldIncludeMemoryItem(item) {
if (!item || typeof item !== 'object') {
return false;
}
const role = item.role;
if (role === 'developer' || role === 'system') {
return false;
}
if (role === 'assistant' || role === 'tool' || role === 'user') {
return true;
}
const type = item.type;
if (typeof type !== 'string') {
return false;
}
if (EXCLUDED_MEMORY_ITEM_TYPES.has(type)) {
return false;
}
return INCLUDED_MEMORY_ITEM_TYPES.has(type);
}
function finalOutputForMemory(state) {
if (state._currentStep?.type !== 'next_step_final_output') {
return null;
}
return state._currentStep.output;
}
function interruptionsForMemory(state) {
return state.getInterruptions();
}
function terminalMetadataForMemory(state, exception, finalOutput) {
if (finalOutput !== null) {
return {
terminal_state: 'completed',
exception_type: null,
exception_message: null,
has_final_output: true,
};
}
if (state._currentStep?.type === 'next_step_interruption') {
return {
terminal_state: 'interrupted',
exception_type: null,
exception_message: null,
has_final_output: false,
};
}
if (exception !== undefined) {
return terminalMetadataForException(exception);
}
return {
terminal_state: 'failed',
exception_type: null,
exception_message: null,
has_final_output: false,
};
}
function terminalMetadataForException(exception) {
const exceptionType = exceptionName(exception);
let terminalState = 'failed';
if (exception instanceof errors_1.MaxTurnsExceededError) {
terminalState = 'max_turns_exceeded';
}
else if (exception instanceof errors_1.InputGuardrailTripwireTriggered ||
exception instanceof errors_1.OutputGuardrailTripwireTriggered ||
exception instanceof errors_1.ToolInputGuardrailTripwireTriggered ||
exception instanceof errors_1.ToolOutputGuardrailTripwireTriggered ||
exceptionType.includes('Guardrail')) {
terminalState = 'guardrail_tripped';
}
else if (exceptionType === 'AbortError' ||
exceptionType === 'CancelledError') {
terminalState = 'cancelled';
}
return {
terminal_state: terminalState,
exception_type: exceptionType,
exception_message: exceptionMessage(exception),
has_final_output: false,
};
}
function exceptionName(exception) {
if (exception instanceof Error && exception.name) {
return exception.name;
}
if (exception &&
typeof exception === 'object' &&
typeof exception.name === 'string') {
return exception.name;
}
return 'Error';
}
function exceptionMessage(exception) {
if (exception instanceof Error) {
return exception.message || null;
}
const message = String(exception);
return message ? message : null;
}
function stringifySortedJson(value) {
return (0, stableJson_1.stableJsonPrettyStringify)(value, {
encodeBytes: (entry) => Object.fromEntries(Object.entries(entry)),
});
}
function utcIsoTimestamp() {
return new Date().toISOString().replace(/Z$/, '+00:00');
}
function sanitizeForMemoryJson(value) {
try {
const serialized = JSON.stringify(value, (_key, childValue) => {
if (childValue instanceof Uint8Array) {
return {
type: 'Uint8Array',
byteLength: childValue.byteLength,
};
}
return childValue;
});
return serialized === undefined ? null : JSON.parse(serialized);
}
catch {
return String(value);
}
}
//# sourceMappingURL=rollouts.js.map