UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

345 lines (344 loc) • 11.7 kB
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import "./text-utility-runtime-Ds8jsG0J.mjs"; import { r as projectAgentToolActivity } from "./agent-activity-events-BvMnPRzr.mjs"; import "./agent-harness-runtime-BCklzcv7.mjs"; import { a as formatNativeToolOutput, c as truncateNativeToolTranscriptText, i as TOOL_TRANSCRIPT_OUTPUT_MAX_CHARS, n as NativeToolOutputAccumulator, o as formatNativeToolSummary, r as TOOL_PROGRESS_OUTPUT_MAX_CHARS, s as formatToolProgressOutput, t as MAX_TOOL_OUTPUT_DELTA_MESSAGES_PER_ITEM } from "./projection-tool-output-DX3_Ng9b.mjs"; import "./agent-harness-attempt-runtime-DFFgKWgF.mjs"; import { i as agentsApiNativeToolOutput, n as agentsApiNativeToolDetails, r as agentsApiNativeToolOutcome, t as agentsApiNativeTool } from "./agentsapi-native-items-zUwQ9-AT.mjs"; import { c as recordAgentsApiNativeToolInvocation, l as recordAgentsApiNativeToolTranscript } from "./agentsapi-transcript-Cs7zhDPb.mjs"; //#region extensions/agentsapi/agentsapi-native-tool-projection.ts /** Native tools own lifecycle, bounded output, and canonical transcript facts. */ var AgentsApiNativeToolProjection = class { constructor(e, t, n, r, i, a) { this.params = e; this.remoteSessionId = t; this.emit = n; this.assertCurrent = r; this.nextTimestamp = i; this.isPresentationEnabled = a; this.items = /* @__PURE__ */ new Map(); this.turnByItem = /* @__PURE__ */ new Map(); this.output = new NativeToolOutputAccumulator("Agents API"); this.metas = /* @__PURE__ */ new Map(); } get toolMetas() { return [...this.metas.values()]; } get lastToolError() { return this.nativeToolError; } get itemLifecycle() { const e = [...this.items.values()]; const t = e.filter((e) => e.terminal).length; return { startedCount: e.length, completedCount: t, activeCount: e.length - t }; } resolveTurnId(e) { return this.turnByItem.get(e); } async recordItem(e, t, n, r, i = false, a = true) { this.assertCurrent(); const o = agentsApiNativeTool(t, this.params); if (!o) return false; const s = this.identity(e, t.id); let c = this.items.get(s); if (c?.terminal && !i) return true; if (!c) { c = { turnId: e, item: t, tool: o, terminal: false, startProjected: false, callRecorded: false, resultRecorded: false, provisionalTerminalObserved: false, canonicalTerminalObserved: false, recoveredPartial: false, outputProgressChars: 0, outputProgressMessages: 0, commandOutputChars: 0, commandOutputMessages: 0 }; this.items.set(s, c); this.turnByItem.set(t.id, e); } c.item = t; c.tool = o; if (i) c.canonicalItem = t; if (i && !n) { c.recoveredPartial = true; if (t.type === "command_execution" && typeof t.output === "string") { c.recoveredOutput = agentsApiNativeToolOutput(t); c.recoveredOutputTruncated = t.output.length > TOOL_TRANSCRIPT_OUTPUT_MAX_CHARS; } } await this.startTool(c); if (i && a && !c.callRecorded) c.callRecorded = await recordAgentsApiNativeToolInvocation(this.params, this.remoteSessionId, e, t, this.assertCurrent, this.nextTimestamp); if (n) await this.finishTool(c, r, i, a); c.terminal = n; return true; } async reconcileRemaining(e, t, n) { this.assertCurrent(); let r = true; for (const i of this.items.values()) { if (i.turnId !== e || i.resultRecorded && i.canonicalTerminalObserved) continue; if (!i.resultRecorded && !n.has(i.item.id)) r = false; await this.finishTool(i, t, true); i.terminal = true; } return r; } async observeOutput(e) { this.assertCurrent(); const t = this.eventItem(e); if (!t || t.terminal || t.recoveredPartial || t.item.type !== "command_execution" || !e.delta) return; const n = this.identity(t.turnId, t.item.id); const r = e.delta; this.output.append(n, r); if (t.commandOutputChars < 8e3 && t.commandOutputMessages < 20) { const e = TOOL_PROGRESS_OUTPUT_MAX_CHARS - t.commandOutputChars; const i = truncateUtf16Safe(r, e); t.commandOutputChars += i.length; t.commandOutputMessages += 1; await this.emit({ stream: "command_output", data: { itemId: n, toolCallId: n, phase: "delta", name: t.tool.name, title: typeof t.tool.args.command === "string" ? t.tool.args.command : "Command output", output: r.length > e ? `${i}\n...(truncated)...` : i, status: "running", ...typeof t.tool.args.cwd === "string" ? { cwd: t.tool.args.cwd } : {} } }); } await this.emitToolOutput(t, e.delta, false); } async startTool(e) { if (e.startProjected) return; const t = this.identity(e.turnId, e.item.id); const { name: n, args: r, meta: i, commandBearing: a } = e.tool; e.startProjected = true; this.metas.set(t, { toolCallId: t, toolName: n, ...i ? { meta: i } : {} }); await this.emit({ stream: "item", data: projectAgentToolActivity({ toolCallId: t, name: n, phase: "start", args: r, meta: i }) }); await this.emit({ stream: "tool", data: { phase: "start", itemId: t, toolCallId: t, name: n, args: r, ...i ? { meta: i } : {}, ...a ? { commandBearing: true } : {} } }); if (this.shouldEmitToolResult()) await this.emitToolProgress(t, formatNativeToolSummary(n, this.formattedMeta(e.tool))); } async finishTool(e, t, n = false, r = true) { const i = this.identity(e.turnId, e.item.id); const a = n ? e.canonicalItem ?? e.item : e.item; const o = n && e.canonicalItem ? agentsApiNativeTool(e.canonicalItem, this.params) : e.tool; if (!o) return; const { name: s, args: c, meta: l, commandBearing: u } = o; const d = n && !e.canonicalItem; const f = d ? { status: t === "cancelled" ? "cancelled" : "unknown", isError: true, outcomeUnknown: t !== "cancelled", error: t === "cancelled" ? "Agents API native tool was cancelled" : "Agents API native tool item is unavailable in saved state" } : agentsApiNativeToolOutcome(a, t); const p = e.recoveredOutput ?? this.output.textByItem.get(i); const m = agentsApiNativeToolOutput(a, p); const h = { ...agentsApiNativeToolDetails(this.remoteSessionId, e.turnId, a, f, p), ...d ? { savedItemAvailability: "unavailable", ...a.type !== "web_search_call" ? { outputAvailability: m === void 0 ? "unavailable" : "partial" } : {} } : {} }; const g = a.output == null && (e.recoveredOutputTruncated || this.output.isTruncated(i)); this.metas.set(i, { toolCallId: i, toolName: s, ...l ? { meta: l } : {}, isError: f.isError }); if (n && r && e.canonicalItem && !e.resultRecorded) e.resultRecorded = await recordAgentsApiNativeToolTranscript(this.params, this.remoteSessionId, e.turnId, e.canonicalItem, this.assertCurrent, this.nextTimestamp, { enclosingStatus: t, capturedOutput: p, captureTruncated: g }); if (n && (e.canonicalItem ? !e.canonicalTerminalObserved : !e.provisionalTerminalObserved)) { this.assertCurrent(); const t = this.params.observeToolTerminal?.({ toolCallId: i, toolName: s, arguments: c, ...l ? { meta: l } : {}, executionStarted: true, outcome: f.isError ? "failure" : "success", ...f.isError ? { failure: { ...f.error ? { error: f.error } : {}, ...f.errorCode ? { errorCode: f.errorCode } : {} } } : {}, nativeMutation: { mutatingAction: a.type !== "web_search_call", replaySafe: a.type === "web_search_call" } }); this.assertCurrent(); if (e.canonicalItem) e.canonicalTerminalObserved = true; else e.provisionalTerminalObserved = true; if (t) this.nativeToolError = t.lastToolError; else if (f.isError) this.nativeToolError = { toolName: s, ...l ? { meta: l } : {}, ...f.error ? { error: f.error } : {}, ...f.errorCode ? { errorCode: f.errorCode } : {}, ...a.type !== "web_search_call" ? { mutatingAction: true } : {} }; else if (this.nativeToolError?.mutatingAction !== true) this.nativeToolError = void 0; } this.assertCurrent(); if (!this.isPresentationEnabled()) return; const _ = u ? { title: typeof c.command === "string" ? c.command : "Command output", ...!d && a.exit_code != null ? { exitCode: a.exit_code } : {}, ...!d && a.duration_ms != null ? { durationMs: a.duration_ms } : {}, ...typeof c.cwd === "string" ? { cwd: c.cwd } : {} } : void 0; const v = m !== void 0 && u ? formatToolProgressOutput(m) ?? "" : m; const y = { phase: "result", itemId: i, toolCallId: i, name: s, args: c, status: f.status, isError: f.isError, result: h, ...v !== void 0 ? { output: v } : {}, ...l ? { meta: l } : {}, ...u ? { commandBearing: true, ..._ } : {} }; const b = projectAgentToolActivity({ toolCallId: i, name: s, phase: "result", args: c, meta: l, status: f.status === "cancelled" ? "unknown" : f.status, result: { details: h }, isError: f.isError }); const x = _ ? { itemId: i, toolCallId: i, phase: "end", name: s, ..._, ...v !== void 0 ? { output: v } : {}, status: f.status } : void 0; const S = sha256Hex(JSON.stringify({ tool: y, item: b, command: x })); if (e.terminalProjectionHash === S) return; const C = { replaceable: true, ...e.terminalProjectionHash ? { replace: true } : {} }; await this.emit({ stream: "tool", data: { ...y, ...C } }); await this.emit({ stream: "item", data: { ...b, ...C } }); if (x) await this.emit({ stream: "command_output", data: { ...x, ...C } }); e.terminalProjectionHash = S; if (m !== void 0 && e.outputProgressMessages === 0) await this.emitToolOutput(e, m, true, f.isError); } async emitToolOutput(e, t, n, r = false) { if (!this.shouldEmitToolOutput() || e.outputProgressChars >= 8e3 || e.outputProgressMessages >= 20) return; const i = TOOL_PROGRESS_OUTPUT_MAX_CHARS - e.outputProgressChars; const a = t.length > i; const o = truncateUtf16Safe(t, i); e.outputProgressChars += o.length; e.outputProgressMessages += 1; await this.emitToolProgress(this.identity(e.turnId, e.item.id), formatNativeToolOutput(e.tool.name, this.formattedMeta(e.tool), a ? `${o}\n...(truncated)...` : o), n && r); } async emitToolProgress(e, t, n = false) { this.assertCurrent(); if (!this.isPresentationEnabled()) return; await this.params.onToolResult?.({ text: truncateNativeToolTranscriptText(t, "Agents API"), ...this.params.messageChannel || this.params.messageProvider ? { channelData: { openclawToolProgressId: `tool:${e}` } } : {}, ...n ? { isError: true } : {} }); this.assertCurrent(); } formattedMeta(e) { return !e.commandBearing || !(this.params.messageChannel ?? this.params.messageProvider) && this.shouldEmitToolOutput() ? e.meta : void 0; } shouldEmitToolResult() { this.assertCurrent(); if (!this.isPresentationEnabled()) return false; return this.params.shouldEmitToolResult?.() ?? (this.params.verboseLevel === "on" || this.params.verboseLevel === "full"); } shouldEmitToolOutput() { this.assertCurrent(); if (!this.isPresentationEnabled()) return false; return this.params.shouldEmitToolOutput?.() ?? this.params.verboseLevel === "full"; } eventItem(e) { if (!e.item_id) throw new Error("Agents API output event has no item identity"); const t = e.turn_id ?? this.turnByItem.get(e.item_id); return t ? this.items.get(this.identity(t, e.item_id)) : void 0; } identity(e, t) { return `agentsapi:${this.remoteSessionId}:${e}:${t}`; } }; //#endregion export { AgentsApiNativeToolProjection as t };