Skip to content
← Public packages

@kody/codex

Create and manage OpenAI Agents API (Codex harness) cloud agent sessions.

src/sessions/delete.ts

60 lines · 1.9 KB · TypeScript
import { boolean, object, optional, parse, string } from 'remix/data-schema'
import { agentsFetch, pickAuth, requireSessionId } from '../client.ts'

const deleteInput = object(
	{
		sessionId: string(),
		/** Must be true for the live DELETE (unless dryRun). */
		confirm: optional(boolean()),
		dryRun: optional(boolean()),
		apiKeySecret: optional(string()),
	},
	{ unknownKeys: 'error' },
)

/**
 * Delete an Agents API session (`DELETE /v1/agents/sessions/{session_id}`).
 * Destructive — requires `confirm: true` (or `dryRun: true` to preview).
 * Save artifacts first; physical cleanup may continue asynchronously.
 *
 * @param raw.sessionId - Session to delete
 * @param raw.confirm - Must be true for the live DELETE
 * @param raw.dryRun - Preview without calling OpenAI
 * @param raw.apiKeySecret - Optional alternate secret name
 * @returns Delete status or dry-run preview
 *
 * @example
 * import deleteSession from 'kody:@kody/codex/sessions/delete'
 * const preview = await deleteSession({ sessionId: 'sess_123', dryRun: true })
 */
export default async function deleteSession(raw: unknown = {}) {
	const input = parse(deleteInput, raw ?? {})
	const auth = pickAuth(input)
	const sessionId = requireSessionId(input.sessionId)
	const path = `/agents/sessions/${encodeURIComponent(sessionId)}`

	if (input.dryRun === true) {
		return {
			dryRun: true as const,
			method: 'DELETE' as const,
			path: `/v1${path}`,
			sessionId,
			note: 'Would delete the session. Save artifacts first. Use confirm: true for live delete.',
		}
	}

	if (input.confirm !== true) {
		throw new Error(
			'Refusing DELETE without confirm: true. Pass dryRun: true to preview, or confirm: true after saving artifacts.',
		)
	}

	const response = await agentsFetch(path, { ...auth, method: 'DELETE' })
	return {
		ok: true,
		deleted: true,
		sessionId,
		result: response.body,
		status: response.status,
	}
}