File size: 8,147 Bytes
4c76b0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// Isolated plugin LLM completion policy validates and dispatches the zero-tool runtime mode.
import { asFiniteNumber } from "@openclaw/normalization-core/number-coercion";
import type { IsolatedCompletionResult } from "../../agents/isolated-completion.js";
import { buildConfiguredModelCatalog } from "../../agents/model-selection-shared.js";
import { resolveEffectiveAgentRuntime } from "../../agents/thinking-runtime.js";
import { resolveThinkingProfile } from "../../auto-reply/thinking.js";
import type { OpenClawConfig } from "../../config/types.openclaw.js";
import { createLlmCompleteError as completionError } from "./runtime-llm-error.js";
import type { LlmCompleteParams, LlmIsolatedAgentRuntimeCompleteParams } from "./types-core.js";

const MAX_TIMER_DELAY_MS = 2_147_483_647;

function requireIsolatedUserPrompt(params: LlmCompleteParams): string {
  if (
    params.execution?.mode !== "isolated-agent-runtime" ||
    !Array.isArray(params.messages) ||
    params.messages.length !== 1 ||
    params.messages[0]?.role !== "user" ||
    typeof params.messages[0].content !== "string"
  ) {
    throw completionError(
      "LLM_ISOLATED_INPUT_REJECTED",
      "Isolated agent-runtime completion requires exactly one user message; pass system instructions through systemPrompt.",
    );
  }
  return params.messages[0].content;
}

export function isIsolatedAgentRuntimeRequest(
  params: LlmCompleteParams,
): params is LlmIsolatedAgentRuntimeCompleteParams {
  return params.execution?.mode === "isolated-agent-runtime";
}

export function assertSupportedExecutionMode(params: LlmCompleteParams): void {
  const execution = (params as { execution?: unknown }).execution;
  if (execution === undefined) {
    return;
  }
  if (
    !execution ||
    typeof execution !== "object" ||
    Array.isArray(execution) ||
    (execution as { mode?: unknown }).mode !== "isolated-agent-runtime"
  ) {
    throw completionError(
      "LLM_ISOLATED_INPUT_REJECTED",
      'Plugin LLM completion execution.mode must be "isolated-agent-runtime" when execution is provided.',
    );
  }
  if (
    ("requiredAuthMode" in params && params.requiredAuthMode !== undefined) ||
    ("responseFormat" in params && params.responseFormat !== undefined)
  ) {
    throw completionError(
      "LLM_ISOLATED_INPUT_REJECTED",
      "Isolated agent-runtime completion does not support requiredAuthMode or responseFormat; use direct completion for provider controls.",
    );
  }
}

function resolveIsolatedTimeoutMs(value: number | undefined): number {
  if (value === undefined) {
    return 30_000;
  }
  const timeoutMs = asFiniteNumber(value);
  if (
    timeoutMs === undefined ||
    !Number.isSafeInteger(timeoutMs) ||
    timeoutMs <= 0 ||
    timeoutMs > MAX_TIMER_DELAY_MS
  ) {
    throw completionError(
      "LLM_ISOLATED_INPUT_REJECTED",
      `Isolated agent-runtime completion timeoutMs must be an integer from 1 through ${MAX_TIMER_DELAY_MS}.`,
    );
  }
  return timeoutMs;
}

function assertIsolatedReasoningSupported(params: {
  cfg: OpenClawConfig;
  agentId: string;
  provider: string;
  model: string;
  reasoning: LlmCompleteParams["reasoning"];
}): void {
  if (params.reasoning === undefined) {
    return;
  }
  const catalog = buildConfiguredModelCatalog({ cfg: params.cfg });
  const profile = resolveThinkingProfile({
    provider: params.provider,
    model: params.model,
    agentRuntime: resolveEffectiveAgentRuntime({
      cfg: params.cfg,
      agentId: params.agentId,
      provider: params.provider,
      modelId: params.model,
    }),
    ...(catalog.length > 0 ? { catalog } : {}),
  });
  if (profile.levels.some((level) => level.id === params.reasoning)) {
    return;
  }
  throw completionError(
    "LLM_ISOLATED_INPUT_REJECTED",
    `Thinking level "${params.reasoning}" is not supported for ${params.provider}/${params.model}. Use one of: ${profile.levels.map((level) => level.label).join(", ")}.`,
  );
}

export async function runIsolatedAgentRuntimeCompletion(params: {
  request: LlmIsolatedAgentRuntimeCompleteParams;
  cfg: OpenClawConfig;
  agentId: string;
  provider: string;
  model: string;
  authProfileId?: string;
}): Promise<IsolatedCompletionResult> {
  const prompt = requireIsolatedUserPrompt(params.request);
  const timeoutMs = resolveIsolatedTimeoutMs(params.request.execution.timeoutMs);
  assertIsolatedReasoningSupported({
    cfg: params.cfg,
    agentId: params.agentId,
    provider: params.provider,
    model: params.model,
    reasoning: params.request.reasoning,
  });
  const controller = new AbortController();
  let timedOut = false;
  const abortFromCaller = () => controller.abort(params.request.signal?.reason);
  if (params.request.signal?.aborted) {
    throw completionError("LLM_COMPLETION_ABORTED", "Plugin LLM completion was aborted.");
  }
  params.request.signal?.addEventListener("abort", abortFromCaller, { once: true });
  const timer = setTimeout(() => {
    timedOut = true;
    controller.abort(new Error(`Isolated completion timed out after ${timeoutMs}ms.`));
  }, timeoutMs);
  timer.unref?.();
  let rejectOnAbort: (() => void) | undefined;
  const abortPromise = new Promise<never>((_resolve, reject) => {
    rejectOnAbort = () => {
      const reason = controller.signal.reason;
      reject(reason instanceof Error ? reason : new Error("Isolated completion was aborted."));
    };
    controller.signal.addEventListener("abort", rejectOnAbort, { once: true });
  });
  try {
    const operation = (async () => {
      const { runIsolatedCompletion } = await import("../../agents/isolated-completion.js");
      return await runIsolatedCompletion({
        config: params.cfg,
        provider: params.provider,
        model: params.model,
        authProfileId: params.authProfileId,
        agentId: params.agentId,
        systemPrompt: params.request.systemPrompt ?? "",
        prompt,
        timeoutMs,
        abortSignal: controller.signal,
        thinkLevel: params.request.reasoning,
        streamParams: {
          maxTokens: asFiniteNumber(params.request.maxTokens),
          temperature: asFiniteNumber(params.request.temperature),
        },
      });
    })();
    return await Promise.race([operation, abortPromise]);
  } catch (error) {
    if (timedOut) {
      throw completionError(
        "LLM_COMPLETION_TIMEOUT",
        `Plugin LLM completion timed out after ${timeoutMs}ms.`,
        error,
      );
    }
    if (params.request.signal?.aborted) {
      throw completionError("LLM_COMPLETION_ABORTED", "Plugin LLM completion was aborted.", error);
    }
    const isolatedError = error as { code?: unknown; message?: unknown };
    if (isolatedError.code === "unsupported") {
      throw completionError(
        "LLM_ISOLATED_UNSUPPORTED",
        typeof isolatedError.message === "string"
          ? isolatedError.message
          : "Configured agent runtime does not support isolated completion.",
        error,
      );
    }
    if (isolatedError.code === "runtime-unavailable") {
      throw completionError(
        "LLM_RUNTIME_UNAVAILABLE",
        typeof isolatedError.message === "string"
          ? isolatedError.message
          : "Configured agent runtime is unavailable.",
        error,
      );
    }
    if (isolatedError.code === "input-rejected") {
      throw completionError(
        "LLM_ISOLATED_INPUT_REJECTED",
        typeof isolatedError.message === "string"
          ? isolatedError.message
          : "Isolated completion input was rejected.",
        error,
      );
    }
    if (isolatedError.code === "output-rejected") {
      throw completionError(
        "LLM_COMPLETION_OUTPUT_REJECTED",
        typeof isolatedError.message === "string"
          ? isolatedError.message
          : "Isolated completion output was rejected.",
        error,
      );
    }
    throw completionError("LLM_COMPLETION_FAILED", "Plugin LLM completion failed.", error);
  } finally {
    clearTimeout(timer);
    if (rejectOnAbort) {
      controller.signal.removeEventListener("abort", rejectOnAbort);
    }
    params.request.signal?.removeEventListener("abort", abortFromCaller);
  }
}