UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

484 lines (483 loc) • 15.2 kB
import { d as sleepWithAbort } from "./src-BPmQBLJp.mjs"; import { Et as _enum, Fn as object, Jn as string, Lt as boolean, Nt as array, Pn as number, Sn as looseObject, Yt as discriminatedUnion, or as union, sr as unknown, xn as literal } from "./schemas-Cy6abvsu.mjs"; import { t as retryAsync } from "./retry-D-ulnYII.mjs"; import { t as omitNullRequestHeaders } from "./request-headers-Dtgiinuk.mjs"; import { d as resolveProviderRequestHeaders } from "./provider-request-config-CCij-nof.mjs"; import { r as fetchWithSsrFGuard, u as responseWithRelease } from "./fetch-guard-BLMw2n18.mjs"; import "./ssrf-runtime-B6q6NM4E.mjs"; import "./retry-runtime-DOUvdfOa.mjs"; import "./fetch-runtime-Dz-KqFMb.mjs"; import "./runtime-env-D-Pa5lD6.mjs"; import "./provider-http-LcawLneq.mjs"; import { randomUUID } from "node:crypto"; import { setTimeout } from "node:timers/promises"; import OpenAI from "openai"; //#region extensions/agentsapi/agentsapi-client.ts const usageSchema = looseObject({ input_tokens: number(), output_tokens: number(), total_tokens: number().optional(), input_tokens_details: looseObject({ cached_tokens: number() }).optional(), output_tokens_details: looseObject({ reasoning_tokens: number() }).optional() }); const errorSchema = looseObject({ message: string(), code: string().nullable().optional(), type: string().optional(), param: string().nullable().optional() }); const functionCallSchema = looseObject({ type: literal("function_call"), turn_id: string().min(1), call_id: string().min(1), name: string().min(1), arguments: unknown() }); const sessionSchema = looseObject({ id: string(), status: _enum([ "idle", "in_progress", "requires_action", "failed" ]), error: string().nullable(), usage: usageSchema.nullable().optional(), environment: discriminatedUnion("type", [ looseObject({ type: literal("openai_hosted"), id: string().min(1) }), looseObject({ type: literal("self_hosted"), id: string().min(1), workspace_directory: string(), remote_url: string().min(1) }), looseObject({ type: literal("none") }) ]), required_actions: array(union([functionCallSchema, looseObject({ type: literal("environment_connection"), environment_id: string() })])) }); const artifactSchema = looseObject({ id: string().min(1), object: literal("agent.session.artifact"), session_id: string(), environment_id: string(), turn_id: string(), path: string(), size_bytes: number().int().nonnegative().safe() }); const textPartSchema = looseObject({ type: string(), text: string().optional() }); const itemSchema = looseObject({ id: string(), type: string(), role: string().optional(), phase: string().nullable().optional(), status: string().nullable().optional(), turn_id: string().optional(), content: array(textPartSchema).optional(), summary: array(textPartSchema).optional(), command: string().optional(), cwd: string().nullable().optional(), duration_ms: number().nullable().optional(), exit_code: number().nullable().optional(), name: string().optional(), call_id: string().optional(), server_label: string().optional(), arguments: unknown().optional(), output: unknown().optional(), error: unknown().optional(), action: looseObject({ type: string(), query: string().nullable().optional(), queries: array(string()).nullable().optional(), url: string().nullable().optional(), pattern: string().nullable().optional() }).nullable().optional() }); const eventSchema = looseObject({ type: string(), event_id: string().optional(), session_id: string().optional(), turn_id: string().nullable().optional(), item_id: string().optional(), output_index: number().nullable().optional(), content_index: number().optional(), summary_index: number().optional(), status: string().nullable().optional(), delta: string().optional(), text: string().optional(), part: textPartSchema.optional(), item: itemSchema.optional(), usage: usageSchema.nullable().optional(), session: sessionSchema.optional(), environment: looseObject({ id: string(), type: string(), status: string(), error: errorSchema.nullable() }).optional(), turn: looseObject({ id: string(), subagent_id: string().nullable(), session_id: string().optional(), status: string().optional(), agent_id: string().optional(), created_at: number().optional(), started_at: number().nullable().optional(), completed_at: number().nullable().optional(), error: errorSchema.nullable().optional(), usage: usageSchema.nullable().optional() }).optional(), error: errorSchema.optional() }); /** The SDK owns the wire protocol; OpenClaw retains native session authority. */ var AgentsApiClient = class { constructor(e, t, n = t) { this.assertCurrent = t; const r = new OpenAI({ apiKey: e, baseURL: null, maxRetries: 0, defaultHeaders: { Authorization: `Bearer ${e}`, "OpenAI-Organization": null, "OpenAI-Project": null }, fetch: async (e, t) => { this.assertCurrent(); const r = e instanceof Request ? e.url : String(e); const i = resolveProviderRequestHeaders({ provider: "openai", baseUrl: r, transport: "http", callerHeaders: Object.fromEntries(new Headers(t?.headers)) }); const a = await fetchWithSsrFGuard({ url: r, init: { ...t, headers: omitNullRequestHeaders(i) }, signal: t?.signal ?? void 0, beforeRequest: n }); const o = responseWithRelease(a.response, a.release); try { this.assertCurrent(); } catch (e) { await o.body?.cancel().catch(() => void 0); throw e; } return o; } }).beta.agents; this.sessions = r.sessions; this.environments = r.environments; } async create(e, t, n, r) { const i = r.environment ?? { type: "openai_hosted" }; const a = [ ...r.nativeTools, ...r.mcpTools, ...r.functions ]; const o = { agent: { model: n, instructions: t, reasoning: r.reasoning, multi_agent: { enabled: false } }, environment: i.type === "openai_hosted" ? { ...i, files: r.files ?? [] } : i }; const s = await this.sessions.create(o, { signal: e, headers: { "Idempotency-Key": randomUUID() }, body: { ...o, agent: { ...o.agent, tools: a } } }); this.assertCurrent(); return s.id; } async createIsolated(e, t, n, r, i) { const a = await this.sessions.create({ agent: { model: r, instructions: t, reasoning: i, tools: [], multi_agent: { enabled: false } }, environment: { type: "none" }, input: n, vault_ids: [] }, { signal: e, headers: { "Idempotency-Key": randomUUID() } }); this.assertCurrent(); return a; } async deleteSession(e, t) { const n = await this.sessions.delete(e, { signal: t }); this.assertCurrent(); if (n.id !== e || !n.deleted) throw new Error("Agents API did not delete the requested isolated session"); } async setReasoningEffort(e, t, n) { const r = await this.sessions.update(e, {}, { signal: n, headers: { "Idempotency-Key": randomUUID() }, body: { agent: { reasoning: { effort: t ?? null } } } }); this.assertCurrent(); if (r.id !== e) throw new Error("Agents API returned a different session"); } async subscribe(e, t) { const n = await this.sessions.events.stream(e, { signal: t }); try { this.assertCurrent(); t.throwIfAborted(); } catch (e) { n.controller.abort(); throw e; } return observeEvents(n, t, e, this.assertCurrent); } async session(e, t) { const n = await this.sessions.retrieve(e, { signal: t }); this.assertCurrent(); if (n.id !== e) throw new Error("Agents API returned a different session"); return n; } async pendingFunctionCalls(e, t) { const n = sessionSchema.parse(await this.session(e, t)); if (n.status === "failed") throw new Error(n.error ?? "Agents API session failed"); if (n.status !== "requires_action") return []; const r = []; for (const e of n.required_actions) { if (e.type === "environment_connection" && n.environment.type === "self_hosted" && e.environment_id === n.environment.id) continue; if (e.type !== "function_call") throw new Error("Agents API hosted prototype cannot reconnect an environment_connection"); r.push(e); } return r; } async toolResult(e, t, n, r) { await this.submitEvents(e, [{ type: "agent.session.input.tool_result", turn_id: t.turn_id, call_id: t.call_id, ...n.success ? { success: true, output: n.output } : { success: false, error: n.error } }], r); } async turn(e, t, n) { const r = await this.sessions.turns.retrieve(t, { session_id: e }, { signal: n }); this.assertCurrent(); if (r.id !== t || r.session_id !== e || r.subagent_id !== null) throw new Error("Agents API returned a turn outside the requested root session"); return r; } async uploadFile(e, t, n) { const r = await this.session(e, n); n.throwIfAborted(); if (r.environment.type !== "openai_hosted") throw new Error("Agents API file upload requires the session's connected hosted environment"); const i = await this.environments.retrieve(r.environment.id, { signal: n }); const a = object({ id: string(), type: literal("openai_hosted"), status: string() }).parse(i); this.assertCurrent(); n.throwIfAborted(); if (a.id !== r.environment.id) throw new Error("Agents API file upload requires the session's connected hosted environment"); if (a.status === "disconnected") return { status: "unavailable" }; if (a.status !== "connected") throw new Error("Agents API file upload requires the session's connected hosted environment"); let o; try { o = await this.environments.files.create(r.environment.id, t, { signal: n, headers: { "Idempotency-Key": randomUUID() } }); } catch (e) { if (e instanceof OpenAI.ConflictError && e.status === 409) { const t = errorSchema.safeParse(e.error); if (t.success && t.data.type === "conflict_error" && t.data.message === "the hosted environment is dormant; submit new input to start a fresh sandbox") { this.assertCurrent(); n.throwIfAborted(); return { status: "unavailable" }; } } throw e; } const s = object({ environment_id: string(), path: string(), size_bytes: number() }).parse(o); this.assertCurrent(); n.throwIfAborted(); if (s.environment_id !== r.environment.id || s.path !== t.path || s.size_bytes !== Buffer.from(t.data, "base64").byteLength) throw new Error("Agents API uploaded file did not match the requested environment, path, or size"); return { status: "uploaded" }; } async artifacts(e, t, n) { const r = []; const i = /* @__PURE__ */ new Set(); let a; for (let o = 0; o < 100; o++) { const o = await this.sessions.artifacts.list(e, { order: "asc", limit: 100, after: a }, { signal: n }); const s = object({ data: array(artifactSchema), has_more: boolean() }).parse(o); this.assertCurrent(); if (s.data.some((t) => t.session_id !== e)) throw new Error("Agents API returned an artifact outside the requested session"); r.push(...s.data.filter((e) => e.turn_id === t)); if (!s.has_more) return r; const c = s.data.at(-1)?.id; if (!c || i.has(c)) throw new Error("Agents API artifacts page has no valid continuation cursor"); a = c; i.add(a); } throw new Error("Agents API artifact listing exceeded the pagination limit"); } async artifactContent(e, t, n, r) { if (t.session_id !== e || !Number.isSafeInteger(n) || n < 0 || t.size_bytes > n) throw new Error("Agents API artifact download exceeds its session or byte bounds"); const i = await this.sessions.artifacts.content(t.id, { session_id: e }, { signal: r }); if (!i.body) throw new Error("Agents API artifact returned no content body"); const a = i.body.getReader(); const o = []; let s = 0; try { while (true) { r.throwIfAborted(); this.assertCurrent(); const e = await a.read(); this.assertCurrent(); if (e.done) break; s += e.value.byteLength; if (s > n || s > t.size_bytes) throw new Error("Agents API artifact content exceeded its immutable size or byte limit"); o.push(e.value); } if (s !== t.size_bytes) throw new Error("Agents API artifact content did not match its immutable size"); return Buffer.concat(o, s); } finally { await closeResponseReader(a, r); } } async turns(e, t, n, r = false) { const i = []; const a = this.sessions.turns.list(e, { order: r ? "desc" : "asc", limit: r ? 1 : 100, after: n }, { signal: t }); for await (const t of (await a).iterPages()) { this.assertCurrent(); if (t.data.some((t) => t.session_id !== e || t.subagent_id !== null)) throw new Error("Agents API returned a turn outside the single-agent session"); i.push(...t.data); if (r) break; if (t.has_more && !t.hasNextPage()) throw new Error("Agents API turns page has no continuation cursor"); } return i; } async message(e, t, n) { await this.submitEvents(e, [{ type: "agent.session.input.message", input: [{ role: "user", content: [{ type: "input_text", text: t }] }] }], n); } async cancel(e, t) { await this.submitEvents(e, [{ type: "agent.session.input.cancel" }], t); while (true) { const n = await this.session(e, t); if (n.status === "idle" || n.status === "failed") return; await setTimeout(500, void 0, { signal: t }); } } async items(e, t, n) { const r = []; const i = this.sessions.items.list(e, { order: "asc", limit: 100 }, { signal: n }); for await (const e of (await i).iterPages()) { this.assertCurrent(); r.push(...e.data.filter((e) => t === void 0 || e.turn_id === t).map((e) => itemSchema.parse(e))); if (e.has_more && !e.hasNextPage()) throw new Error("Agents API items page has no continuation cursor"); } return r; } async submitEvents(e, t, n) { const r = { events: t, "Idempotency-Key": randomUUID() }; await retryAsync(async () => { n.throwIfAborted(); this.assertCurrent(); await this.sessions.events.create(e, r, { signal: n }); }, { attempts: 3, minDelayMs: 500, maxDelayMs: 5e3, jitter: .25, shouldRetry: (e) => !n.aborted && e instanceof OpenAI.APIError && e.status !== void 0 && e.status >= 500 && e.status < 600 && e.headers?.get("x-should-retry") !== "false", sleep: (e) => sleepWithAbort(e, n) }); this.assertCurrent(); } }; function isAgentsApiTerminalTurn(e) { return e === "completed" || e === "failed" || e === "cancelled"; } async function* observeEvents(e, t, n, r) { for await (const i of e) { t.throwIfAborted(); r(); const e = eventSchema.parse(i); if (e.session_id && e.session_id !== n || e.session && e.session.id !== n || e.turn?.session_id && e.turn.session_id !== n) throw new Error("Agents API returned an event outside the requested session"); yield e; } t.throwIfAborted(); } async function closeResponseReader(e, t) { try { await e.cancel(); } catch (e) { if (!t.aborted) throw e; } finally { e.releaseLock(); } t.throwIfAborted(); } //#endregion export { isAgentsApiTerminalTurn as n, AgentsApiClient as t };