File size: 9,938 Bytes
f778c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/** Applies runtime mode/config controls to live ACP backend sessions. */
import type {
  AcpRuntime,
  AcpRuntimeCapabilities,
  AcpRuntimeHandle,
  AcpRuntimeStatus,
} from "@openclaw/acp-core/runtime/types";
import { asNullableRecord } from "@openclaw/normalization-core/record-coerce";
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
import {
  AcpRuntimeError,
  formatAcpErrorChain,
  toAcpRuntimeError,
  withAcpRuntimeErrorBoundary,
} from "../runtime/errors.js";
import type { CachedRuntimeState } from "./manager.runtime-handle-cache.js";
import { isAcpOwnerRepairRequired } from "./manager.runtime-owner.js";
import type { AcpSessionRuntimeOptions, SessionAcpMeta } from "./manager.types.js";
import { createUnsupportedControlError } from "./manager.utils.js";
import {
  buildRuntimeConfigOptionPairs,
  buildRuntimeControlSignature,
  isThinkingConfigKey,
  normalizeText,
  reconcileAcceptedRuntimeOptions,
  resolveRuntimeConfigOptionKey,
  resolveRuntimeOptionsFromMeta,
  runtimeOptionsEqual,
} from "./runtime-options.js";

const OPTIONAL_TIMEOUT_CONFIG_KEYS = new Set(["timeout", "timeout_seconds"]);
const ACP_CONFIG_REJECTION_CODE_RE = /-3260[23]/;
const CONFIG_OPTION_REJECTION_RE =
  /invalid params|unsupported|not supported|not implement|invalid value|unknown config option|unknown value|not a valid value|must be one of/;

function extractConfigOptionKeys(value: unknown): string[] {
  if (!Array.isArray(value)) {
    return [];
  }
  return value
    .map((entry) => {
      if (typeof entry === "string") {
        return normalizeText(entry);
      }
      const record = asNullableRecord(entry);
      return normalizeText(record?.id ?? record?.key);
    })
    .filter(Boolean) as string[];
}

function extractRuntimeStatusConfigOptionKeys(status: AcpRuntimeStatus | undefined): string[] {
  const details = asNullableRecord(status?.details);
  return [
    ...extractConfigOptionKeys(details?.configOptions),
    ...extractConfigOptionKeys(details?.config_options),
  ];
}

function isOptionalTimeoutConfigKey(key: string): boolean {
  return OPTIONAL_TIMEOUT_CONFIG_KEYS.has(normalizeLowercaseStringOrEmpty(key));
}

function isUnsupportedControlRejection(error: unknown): boolean {
  const errorCode = error && typeof error === "object" ? (error as { code?: unknown }).code : null;
  return errorCode === "ACP_BACKEND_UNSUPPORTED_CONTROL";
}

function describeConfigOptionRejection(error: unknown): string {
  const described = toAcpRuntimeError({
    error,
    fallbackCode: "ACP_TURN_FAILED",
    fallbackMessage: "",
  });
  return normalizeLowercaseStringOrEmpty(`${formatAcpErrorChain(error)} ${described.message}`);
}

function isUnsupportedOptionalTimeoutConfigRejection(key: string, error: unknown): boolean {
  if (!isOptionalTimeoutConfigKey(key)) {
    return false;
  }
  if (isUnsupportedControlRejection(error)) {
    return true;
  }
  const message =
    error instanceof Error ? error.message : typeof error === "string" ? error : String(error);
  const normalized = normalizeLowercaseStringOrEmpty(message);
  return (
    normalized.includes("session/set_config_option") &&
    (normalized.includes("-32602") ||
      normalized.includes("invalid params") ||
      normalized.includes("unsupported") ||
      normalized.includes("not supported") ||
      normalized.includes("not implement"))
  );
}

function isRejectedThinkingConfigOption(key: string, error: unknown): boolean {
  if (!isThinkingConfigKey(key)) {
    return false;
  }
  if (isUnsupportedControlRejection(error)) {
    return true;
  }
  const description = describeConfigOptionRejection(error);
  const describesConfigOption =
    description.includes("session/set_config_option") ||
    (description.includes("config option") &&
      description.includes(normalizeLowercaseStringOrEmpty(key)));
  return (
    describesConfigOption &&
    ACP_CONFIG_REJECTION_CODE_RE.test(description) &&
    CONFIG_OPTION_REJECTION_RE.test(description)
  );
}

/** Resolves backend-advertised controls plus locally inferred runtime control support. */
export async function resolveManagerRuntimeCapabilities(params: {
  runtime: AcpRuntime;
  handle: AcpRuntimeHandle;
  includeStatusConfigOptionKeys?: boolean;
}): Promise<AcpRuntimeCapabilities> {
  let reported: AcpRuntimeCapabilities | undefined;
  if (params.runtime.getCapabilities) {
    reported = await withAcpRuntimeErrorBoundary({
      run: async () => await params.runtime.getCapabilities!({ handle: params.handle }),
      fallbackCode: "ACP_TURN_FAILED",
      fallbackMessage: "Could not read ACP runtime capabilities.",
    });
  }
  const controls = new Set<AcpRuntimeCapabilities["controls"][number]>(reported?.controls ?? []);
  if (params.runtime.setMode) {
    controls.add("session/set_mode");
  }
  if (params.runtime.setConfigOption) {
    controls.add("session/set_config_option");
  }
  if (params.runtime.getStatus) {
    controls.add("session/status");
  }
  const normalizedKeys = new Set(
    (reported?.configOptionKeys ?? [])
      .map((entry) => normalizeText(entry))
      .filter(Boolean) as string[],
  );
  if (
    normalizedKeys.size === 0 &&
    params.includeStatusConfigOptionKeys &&
    params.runtime.getStatus
  ) {
    try {
      const status = await params.runtime.getStatus({ handle: params.handle });
      for (const key of extractRuntimeStatusConfigOptionKeys(status)) {
        normalizedKeys.add(key);
      }
    } catch (error) {
      if (isAcpOwnerRepairRequired(error)) {
        throw error;
      }
      // Status-derived option keys are an optional refinement. Keep the
      // capability result usable for runtimes that expose controls but cannot
      // answer status before a turn.
    }
  }
  return {
    controls: [...controls].toSorted(),
    ...(normalizedKeys.size > 0 ? { configOptionKeys: [...normalizedKeys] } : {}),
  };
}

/** Applies persisted runtime options to a live handle once per unique option signature. */
export async function applyManagerRuntimeControls(params: {
  sessionKey: string;
  runtime: AcpRuntime;
  handle: AcpRuntimeHandle;
  meta: SessionAcpMeta;
  getCachedRuntimeState: (sessionKey: string) => CachedRuntimeState | null;
  onOptionsChanged: (options: AcpSessionRuntimeOptions) => Promise<void>;
}): Promise<void> {
  let options = resolveRuntimeOptionsFromMeta(params.meta);
  const signature = buildRuntimeControlSignature(options);
  const cached = params.getCachedRuntimeState(params.sessionKey);
  if (cached?.appliedControlSignature === signature) {
    return;
  }

  const needsConfigOptionKeys = buildRuntimeConfigOptionPairs(options).length > 0;
  const capabilities = await resolveManagerRuntimeCapabilities({
    runtime: params.runtime,
    handle: params.handle,
    includeStatusConfigOptionKeys: needsConfigOptionKeys,
  });
  const backend = params.handle.backend || params.meta.backend;
  const runtimeMode = normalizeText(options.runtimeMode);
  const configOptions = buildRuntimeConfigOptionPairs(options, capabilities.configOptionKeys);
  const thinkingConfigKey = options.thinking
    ? resolveRuntimeConfigOptionKey("thinking", capabilities.configOptionKeys)
    : undefined;
  const advertisedKeys = new Set(
    (capabilities.configOptionKeys ?? [])
      .map((entry) => normalizeLowercaseStringOrEmpty(entry))
      .filter(Boolean),
  );

  await withAcpRuntimeErrorBoundary({
    run: async () => {
      if (runtimeMode) {
        if (!capabilities.controls.includes("session/set_mode") || !params.runtime.setMode) {
          throw createUnsupportedControlError({
            backend,
            control: "session/set_mode",
          });
        }
        await params.runtime.setMode({
          handle: params.handle,
          mode: runtimeMode,
        });
      }

      if (configOptions.length > 0) {
        if (
          !capabilities.controls.includes("session/set_config_option") ||
          !params.runtime.setConfigOption
        ) {
          throw createUnsupportedControlError({
            backend,
            control: "session/set_config_option",
          });
        }
        for (const [key, requestedValue] of configOptions) {
          // Model changes can clamp or remove unsupported thinking before its turn in the replay.
          const value = key === thinkingConfigKey ? options.thinking : requestedValue;
          if (value === undefined) {
            continue;
          }
          if (
            advertisedKeys.size > 0 &&
            !advertisedKeys.has(normalizeLowercaseStringOrEmpty(key))
          ) {
            throw new AcpRuntimeError(
              "ACP_BACKEND_UNSUPPORTED_CONTROL",
              `ACP backend "${backend}" does not accept config key "${key}".`,
            );
          }
          try {
            const result = await params.runtime.setConfigOption({
              handle: params.handle,
              key,
              value,
            });
            const accepted = reconcileAcceptedRuntimeOptions(
              options,
              result,
              normalizeLowercaseStringOrEmpty(key) === "model" ? options.thinking : undefined,
            );
            if (!runtimeOptionsEqual(options, accepted)) {
              // Persist each accepted change even if a later control fails.
              await params.onOptionsChanged(accepted);
              options = accepted;
            }
          } catch (error) {
            if (
              isUnsupportedOptionalTimeoutConfigRejection(key, error) ||
              isRejectedThinkingConfigOption(key, error)
            ) {
              continue;
            }
            throw error;
          }
        }
      }
    },
    fallbackCode: "ACP_TURN_FAILED",
    fallbackMessage: "Could not apply ACP runtime options before turn execution.",
  });

  if (cached) {
    cached.appliedControlSignature = buildRuntimeControlSignature(options);
  }
}