UNPKG

@openai/agents-openai

Version:

The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows.

548 lines • 23.6 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.OpenAIResponsesCompactionSession = void 0; const openai_1 = __importDefault(require("openai")); const agents_core_1 = require("@openai/agents-core"); const internal_1 = require("@openai/agents-core/utils/internal"); const defaults_1 = require("../defaults.js"); const openaiResponsesModel_1 = require("../openaiResponsesModel.js"); const openaiSessionApi_1 = require("./openaiSessionApi.js"); const DEFAULT_COMPACTION_THRESHOLD = 10; const logger = (0, agents_core_1.getLogger)('openai-agents:openai:compaction'); /** * Session decorator that triggers `responses.compact` when the stored history grows. * * This session is intended to be passed to `run()` so the runner can automatically supply the * latest `responseId` and invoke compaction after each completed turn is persisted. * Automatic compaction skips history that is not fully covered by the latest successful model * input and response. It also waits for function call results and hosted MCP approval responses * before compacting those groups. Explicit manual compaction remains caller-controlled. * * To debug compaction decisions, enable the `debug` logger for * `openai-agents:openai:compaction` (for example, `DEBUG=openai-agents:openai:compaction`). */ class OpenAIResponsesCompactionSession { [openaiSessionApi_1.OPENAI_SESSION_API] = 'responses'; client; underlyingSession; model; compactionMode; maxRollbackItems; responseId; lastStore; shouldTriggerCompaction; compactionCandidateItems; sessionItems; mutationOperation = Promise.resolve(); mutationGeneration = {}; compactionOwnership = new WeakMap(); constructor(options) { const { maxRollbackItems } = options; if (maxRollbackItems !== undefined && (!Number.isSafeInteger(maxRollbackItems) || maxRollbackItems <= 0 || !Number.isSafeInteger(maxRollbackItems + 1))) { throw new agents_core_1.UserError('maxRollbackItems must be a positive integer whose value plus one is a safe integer.'); } this.maxRollbackItems = maxRollbackItems; this.client = resolveClient(options); if (isOpenAIConversationsSessionDelegate(options.underlyingSession)) { throw new agents_core_1.UserError('OpenAIResponsesCompactionSession does not support OpenAIConversationsSession as an underlying session.'); } this.underlyingSession = options.underlyingSession ?? new agents_core_1.MemorySession(); const model = (options.model ?? defaults_1.DEFAULT_OPENAI_MODEL).trim(); assertSupportedOpenAIResponsesCompactionModel(model); this.model = model; this.compactionMode = options.compactionMode ?? 'auto'; this.shouldTriggerCompaction = options.shouldTriggerCompaction ?? defaultShouldTriggerCompaction; this.compactionCandidateItems = undefined; this.sessionItems = undefined; this.lastStore = undefined; } async runCompaction(args = {}, _runContext, ownership, modelExchange) { return this.runMutationOperation(async () => { if (ownership !== undefined && !this.ownsCompaction(ownership)) { logger.debug('skip: automatic compaction no longer owns session history'); return null; } let automaticInput; if (ownership !== undefined) { if (!modelExchange) return null; if ((args.compactionMode ?? this.compactionMode) === 'previous_response_id' && !modelExchange.responseId) return null; // An explicit finite limit avoids mistaking a backend's default window for all history. const history = await this.underlyingSession.getItems(modelExchange.items.length + 1); automaticInput = (0, internal_1.getModelVisibleSessionItems)(this, history, modelExchange); if (!automaticInput || automaticInput.length === 0) { logger.debug('skip: stored history is not covered by the successful model exchange'); return null; } // Keep decisions tied to the actual complete snapshot, not a stale candidate cache. this.sessionItems = history; this.compactionCandidateItems = selectCompactionCandidateItems(history); this.responseId = modelExchange.responseId; args = { ...args, responseId: modelExchange.responseId }; } const result = await this.runCompactionOperation(args, automaticInput); if (result && ownership) { this.compactionOwnership.set(ownership, this.mutationGeneration); } return result; }); } async runCompactionOperation(args, automaticInput) { this.responseId = args.responseId ?? this.responseId ?? undefined; if (args.store !== undefined) { this.lastStore = args.store; } // Manual compaction still needs the response ID and store setting of a paused turn. if (automaticInput && !(0, internal_1.hasCompleteApprovalGroups)(automaticInput)) { logger.debug('skip: stored history has an incomplete approval group'); return null; } const requestedMode = args.compactionMode ?? this.compactionMode; const resolvedMode = resolveCompactionMode({ requestedMode, responseId: this.responseId, store: args.store ?? this.lastStore, }); if (resolvedMode === 'previous_response_id' && !this.responseId) { throw new agents_core_1.UserError('OpenAIResponsesCompactionSession.runCompaction requires a responseId from the last completed turn when using previous_response_id compaction.'); } if (args.force === true && this.maxRollbackItems !== undefined) { // Forced calls do not need a decision hook or potentially unlimited candidates first. await this.getAllUnderlyingSessionItems(); } const { compactionCandidateItems, sessionItems } = await this.ensureCompactionCandidates(); const shouldTriggerCompaction = args.force === true ? true : await this.shouldTriggerCompaction({ responseId: this.responseId, compactionMode: resolvedMode, compactionCandidateItems: structuredClone(compactionCandidateItems), sessionItems: structuredClone(sessionItems), }); if (!shouldTriggerCompaction) { logger.debug('skip: decision hook %o', { responseId: this.responseId, compactionMode: resolvedMode, }); return null; } if (args.force !== true && this.maxRollbackItems !== undefined) { await this.getAllUnderlyingSessionItems(); } logger.debug('compact: start %o', { responseId: this.responseId, model: this.model, compactionMode: resolvedMode, }); const compactRequest = { model: this.model, }; if (resolvedMode === 'previous_response_id') { compactRequest.previous_response_id = this.responseId; } else { compactRequest.input = (0, openaiResponsesModel_1.getInputItems)(automaticInput ?? sessionItems); } const compacted = await this.client.responses.compact(compactRequest); const outputItems = normalizeCompactionOutputItems(compacted.output ?? []); const outputCompactionCandidateItems = selectCompactionCandidateItems(outputItems); // Refresh after the request so rollback does not revive items that expired during the await. let previousItems; try { previousItems = await this.getAllUnderlyingSessionItems(); } catch (error) { const usage = toRequestUsage(compacted.usage); (0, internal_1.attachModelFailureUsage)(error, new agents_core_1.Usage({ ...usage, requests: 1, requestUsageEntries: [usage] })); throw error; } try { await this.replaceUnderlyingSessionItems({ outputItems, previousItems }); } catch (error) { this.compactionCandidateItems = undefined; this.sessionItems = undefined; throw error; } finally { this.mutationGeneration = {}; } this.compactionCandidateItems = outputCompactionCandidateItems; this.sessionItems = outputItems; logger.debug('compact: done %o', { responseId: this.responseId, compactionMode: resolvedMode, outputItemCount: outputItems.length, candidateCount: outputCompactionCandidateItems.length, }); return { usage: toRequestUsage(compacted.usage), }; } async getSessionId() { return this.underlyingSession.getSessionId(); } async getItems(limit) { return this.underlyingSession.getItems(limit); } async getItemsWithCompactionOwnership(_runContext) { return this.runMutationOperation(async () => { const items = await this.underlyingSession.getItems(); const ownership = {}; this.compactionOwnership.set(ownership, this.mutationGeneration); return { items, ownership }; }); } prepareHistoryItemsForPersistenceComparison(items) { const prepare = this.underlyingSession.prepareHistoryItemsForPersistenceComparison; return prepare ? prepare.call(this.underlyingSession, items) : items; } async addItems(items) { await this.addItemsWithCompactionOwnership(items, null); } async addItemsWithCompactionOwnership(items, ownership, _runContext) { if (items.length === 0) { return; } await this.runMutationOperation(async () => { const ownsGeneration = this.ownsCompaction(ownership); try { await this.underlyingSession.addItems(items); } catch (error) { // The backend may have committed before its acknowledgement was lost. Cached history // cannot distinguish that outcome, so force the next compaction decision to reload it. this.compactionCandidateItems = undefined; this.sessionItems = undefined; throw error; } finally { this.mutationGeneration = {}; } if (ownsGeneration && ownership) { this.compactionOwnership.set(ownership, this.mutationGeneration); } if (this.compactionCandidateItems) { const candidates = selectCompactionCandidateItems(items); if (candidates.length > 0) { this.compactionCandidateItems = [ ...this.compactionCandidateItems, ...candidates, ]; } } if (this.sessionItems) { this.sessionItems = [...this.sessionItems, ...items]; } }); } async popItem() { return this.runMutationOperation(async () => { let popped; try { popped = await this.underlyingSession.popItem(); } catch (error) { this.mutationGeneration = {}; this.responseId = undefined; this.lastStore = undefined; this.compactionCandidateItems = undefined; this.sessionItems = undefined; throw error; } if (!popped) { return popped; } this.mutationGeneration = {}; this.responseId = undefined; this.lastStore = undefined; // A successful destructive mutation makes both cached history views stale. // Do not try to repair them from the returned item: some backends clone // values, and a refresh can fail after the pop has already committed. // The next compaction decision will reload authoritative persisted history. this.compactionCandidateItems = undefined; this.sessionItems = undefined; return popped; }); } async clearSession() { await this.runMutationOperation(async () => { try { await this.underlyingSession.clearSession(); } catch (error) { this.compactionCandidateItems = undefined; this.sessionItems = undefined; throw error; } finally { this.mutationGeneration = {}; this.responseId = undefined; this.lastStore = undefined; } this.compactionCandidateItems = []; this.sessionItems = []; }); } ownsCompaction(ownership) { return (ownership !== null && this.compactionOwnership.get(ownership) === this.mutationGeneration); } runMutationOperation(operation) { const result = this.mutationOperation.then(operation); this.mutationOperation = result.then(() => undefined, () => undefined); return result; } async getAllUnderlyingSessionItems() { if (this.maxRollbackItems === undefined) { return this.underlyingSession.getItems(); } const items = await this.underlyingSession.getItems(this.maxRollbackItems + 1); if (items.length > this.maxRollbackItems) { this.sessionItems = undefined; this.compactionCandidateItems = undefined; throw new agents_core_1.UserError('Compaction history exceeds maxRollbackItems; history was retained.'); } return items; } async replaceUnderlyingSessionItems({ outputItems, previousItems, }) { try { await this.underlyingSession.clearSession(); } catch (error) { await this.restoreUnderlyingSessionItemsAfterFailedClear(previousItems, error); throw error; } try { if (outputItems.length > 0) { await this.underlyingSession.addItems(outputItems); } } catch (error) { await this.restoreUnderlyingSessionItems(previousItems, error); throw error; } } async restoreUnderlyingSessionItemsAfterFailedClear(previousItems, error) { let currentItems; try { currentItems = await this.getAllUnderlyingSessionItems(); } catch (inspectionError) { (0, internal_1.logModelAndToolActionWarning)(logger, 'Failed to inspect session history after compaction replacement clear failed.', inspectionError); return; } if (areAgentItemsEqual(currentItems, previousItems)) { return; } await this.restoreUnderlyingSessionItems(previousItems, error, { popExistingItemCount: currentItems.length, }); } async restoreUnderlyingSessionItems(previousItems, error, options = {}) { try { if (options.popExistingItemCount !== undefined) { for (let i = 0; i < options.popExistingItemCount; i += 1) { const popped = await this.underlyingSession.popItem(); if (!popped) { break; } } } else if (options.clearExistingItems !== false) { await this.underlyingSession.clearSession(); } if (previousItems.length > 0) { await this.underlyingSession.addItems(previousItems); } } catch (restoreError) { (0, internal_1.logModelAndToolActionWarning)(logger, 'Failed to restore session history after compaction replacement failed.', restoreError); return; } (0, internal_1.logModelAndToolActionWarning)(logger, 'Restored previous session history after compaction replacement failed.', error); } async ensureCompactionCandidates() { if (this.compactionCandidateItems && this.sessionItems) { logger.debug('candidates: cached %o', { candidateCount: this.compactionCandidateItems.length, }); return { compactionCandidateItems: [...this.compactionCandidateItems], sessionItems: [...this.sessionItems], }; } const history = await this.underlyingSession.getItems(); const compactionCandidates = selectCompactionCandidateItems(history); this.compactionCandidateItems = compactionCandidates; this.sessionItems = history; logger.debug('candidates: initialized %o', { historyLength: history.length, candidateCount: compactionCandidates.length, }); return { compactionCandidateItems: [...compactionCandidates], sessionItems: [...history], }; } } exports.OpenAIResponsesCompactionSession = OpenAIResponsesCompactionSession; function resolveCompactionMode(options) { const { requestedMode, responseId, store } = options; if (requestedMode !== 'auto') { return requestedMode; } if (store === false) { return 'input'; } if (!responseId) { return 'input'; } return 'previous_response_id'; } function resolveClient(options) { if (options.client) { return options.client; } const defaultClient = (0, defaults_1.getDefaultOpenAIClient)(); if (defaultClient) { return defaultClient; } return new openai_1.default(); } function defaultShouldTriggerCompaction({ compactionCandidateItems, }) { return compactionCandidateItems.length >= DEFAULT_COMPACTION_THRESHOLD; } function selectCompactionCandidateItems(items) { return items.filter((item) => { if (item.type === 'compaction') { return false; } return !(item.type === 'message' && item.role === 'user'); }); } function assertSupportedOpenAIResponsesCompactionModel(model) { if (!isOpenAIModelName(model)) { throw new Error(`Unsupported model for OpenAI responses compaction: ${JSON.stringify(model)}`); } } function isOpenAIModelName(model) { const modelName = model.slice(model.lastIndexOf('/') + 1); // The OpenAI SDK does not ship a runtime allowlist of model names. // This check relies on common model naming conventions and intentionally allows unknown `gpt-*` variants. // Fine-tuned model IDs typically look like: ft:gpt-4o-mini:org:project:suffix. const withoutFineTunePrefix = modelName.startsWith('ft:') ? modelName.slice('ft:'.length) : modelName; const root = withoutFineTunePrefix.split(':', 1)[0]; // Allow unknown `gpt-*` variants to avoid needing updates whenever new models ship. if (root.startsWith('gpt-')) { return true; } // Allow the `o*` reasoning models if (/^o\d[a-z0-9-]*$/i.test(root)) { return true; } return false; } function toRequestUsage(usage) { return new agents_core_1.RequestUsage({ inputTokens: usage?.input_tokens ?? 0, outputTokens: usage?.output_tokens ?? 0, totalTokens: usage?.total_tokens ?? 0, inputTokensDetails: { ...usage?.input_tokens_details }, outputTokensDetails: { ...usage?.output_tokens_details }, endpoint: 'responses.compact', }); } function normalizeCompactionOutputItems(items) { return items.flatMap((item) => { if (isCompactionInputMessage(item)) { return [normalizeCompactionInputMessage(item)]; } return [item]; }); } function isCompactionInputMessage(item) { return item.type === 'message' && item.role === 'user'; } function normalizeCompactionInputMessage(item) { return { id: item.id, type: 'message', role: 'user', content: item.content.map((content) => { if (content.type === 'input_text') { return { type: 'input_text', text: content.text, }; } if (content.type === 'input_image') { if (typeof content.image_url === 'string' && content.image_url.length > 0) { return { type: 'input_image', image: content.image_url, ...(content.detail ? { detail: content.detail } : {}), }; } if (typeof content.file_id === 'string' && content.file_id.length > 0) { return { type: 'input_image', image: { id: content.file_id }, ...(content.detail ? { detail: content.detail } : {}), }; } throw new agents_core_1.UserError('Compaction input_image item missing image_url or file_id.'); } if (content.type === 'input_file') { if (typeof content.file_data === 'string' && content.file_data.length > 0) { return { type: 'input_file', file: content.file_data, ...(content.filename ? { filename: content.filename } : {}), }; } if (typeof content.file_url === 'string' && content.file_url.length > 0) { return { type: 'input_file', file: content.file_url, ...(content.filename ? { filename: content.filename } : {}), }; } if (typeof content.file_id === 'string' && content.file_id.length > 0) { return { type: 'input_file', file: { id: content.file_id }, ...(content.filename ? { filename: content.filename } : {}), }; } throw new agents_core_1.UserError('Compaction input_file item missing file_data, file_url, or file_id.'); } throw new agents_core_1.UserError(`Unsupported compaction message content type: ${JSON.stringify(content)}`); }), }; } function isOpenAIConversationsSessionDelegate(underlyingSession) { return (!!underlyingSession && typeof underlyingSession === 'object' && openaiSessionApi_1.OPENAI_SESSION_API in underlyingSession && underlyingSession[openaiSessionApi_1.OPENAI_SESSION_API] === 'conversations'); } function areAgentItemsEqual(left, right) { return JSON.stringify(left) === JSON.stringify(right); } //# sourceMappingURL=openaiResponsesCompactionSession.js.map