diff --git a/charts/openshell-rhdh/files/create-workspace-for-user.yaml b/charts/openshell-rhdh/files/create-workspace-for-user.yaml index a1d46dcd..16bb26ba 100644 --- a/charts/openshell-rhdh/files/create-workspace-for-user.yaml +++ b/charts/openshell-rhdh/files/create-workspace-for-user.yaml @@ -60,6 +60,10 @@ spec: inference__url: {title: 'inference: Endpoint base URL (OpenAI-compatible, ending in /v1)', type: string, pattern: '^https?://'} inference__model: {title: 'inference: Model', type: string} + inference__thinking: {title: 'inference: Default thinking level', type: string} + inference__reasoning: {title: 'inference: Reasoning model (true or false)', type: string} + inference__max_tokens: {title: 'inference: Maximum output tokens', type: string} + inference__context_window: {title: 'inference: Context window (tokens)', type: string} required: [inference__api_key, inference__url, inference__model] allOf: - if: @@ -116,11 +120,13 @@ spec: stringData: {action: create, token: '${{ secrets.backstageToken }}', profile: '${{ parameters.profile }}', deploymentMode: '${{ parameters.deploymentMode }}', forUser: '${{ parameters.forUser }}', inference.api_key: '${{ secrets.inference__api_key }}', inference.url: '${{ parameters.inference__url - }}', inference.model: '${{ parameters.inference__model }}', web-search.api_key: '${{ secrets.web_search__api_key - }}', inference.cuda_model: '${{ parameters.inference__cuda_model }}', gmail.client_id: '${{ - secrets.gmail__client_id }}', gmail.client_secret: '${{ secrets.gmail__client_secret }}', - gmail.refresh_token: '${{ secrets.gmail__refresh_token }}', slack.bot_token: '${{ secrets.slack__bot_token - }}'} + }}', inference.model: '${{ parameters.inference__model }}', inference.thinking: '${{ parameters.inference__thinking + }}', inference.reasoning: '${{ parameters.inference__reasoning }}', inference.max_tokens: '${{ + parameters.inference__max_tokens }}', inference.context_window: '${{ parameters.inference__context_window + }}', web-search.api_key: '${{ secrets.web_search__api_key }}', inference.cuda_model: '${{ + parameters.inference__cuda_model }}', gmail.client_id: '${{ secrets.gmail__client_id }}', + gmail.client_secret: '${{ secrets.gmail__client_secret }}', gmail.refresh_token: '${{ secrets.gmail__refresh_token + }}', slack.bot_token: '${{ secrets.slack__bot_token }}'} - id: run name: Start the pipeline action: http:backstage:request diff --git a/charts/openshell-rhdh/files/create-workspace.yaml b/charts/openshell-rhdh/files/create-workspace.yaml index 64e754a7..35636673 100644 --- a/charts/openshell-rhdh/files/create-workspace.yaml +++ b/charts/openshell-rhdh/files/create-workspace.yaml @@ -52,6 +52,10 @@ spec: inference__url: {title: 'inference: Endpoint base URL (OpenAI-compatible, ending in /v1)', type: string, pattern: '^https?://'} inference__model: {title: 'inference: Model', type: string} + inference__thinking: {title: 'inference: Default thinking level', type: string} + inference__reasoning: {title: 'inference: Reasoning model (true or false)', type: string} + inference__max_tokens: {title: 'inference: Maximum output tokens', type: string} + inference__context_window: {title: 'inference: Context window (tokens)', type: string} required: [inference__api_key, inference__url, inference__model] allOf: - if: @@ -108,10 +112,13 @@ spec: stringData: {action: create, token: '${{ secrets.backstageToken }}', profile: '${{ parameters.profile }}', deploymentMode: '${{ parameters.deploymentMode }}', inference.api_key: '${{ secrets.inference__api_key }}', inference.url: '${{ parameters.inference__url }}', inference.model: '${{ parameters.inference__model - }}', web-search.api_key: '${{ secrets.web_search__api_key }}', inference.cuda_model: '${{ - parameters.inference__cuda_model }}', gmail.client_id: '${{ secrets.gmail__client_id }}', - gmail.client_secret: '${{ secrets.gmail__client_secret }}', gmail.refresh_token: '${{ secrets.gmail__refresh_token - }}', slack.bot_token: '${{ secrets.slack__bot_token }}'} + }}', inference.thinking: '${{ parameters.inference__thinking }}', inference.reasoning: '${{ + parameters.inference__reasoning }}', inference.max_tokens: '${{ parameters.inference__max_tokens + }}', inference.context_window: '${{ parameters.inference__context_window }}', web-search.api_key: '${{ + secrets.web_search__api_key }}', inference.cuda_model: '${{ parameters.inference__cuda_model + }}', gmail.client_id: '${{ secrets.gmail__client_id }}', gmail.client_secret: '${{ secrets.gmail__client_secret + }}', gmail.refresh_token: '${{ secrets.gmail__refresh_token }}', slack.bot_token: '${{ secrets.slack__bot_token + }}'} - id: run name: Start the pipeline action: http:backstage:request diff --git a/charts/openshell-rhdh/files/profile-catalog.json b/charts/openshell-rhdh/files/profile-catalog.json index e8edccb1..177273d4 100644 --- a/charts/openshell-rhdh/files/profile-catalog.json +++ b/charts/openshell-rhdh/files/profile-catalog.json @@ -79,6 +79,30 @@ "kind": "text", "required": true, "title": "Model" + }, + { + "key": "thinking", + "kind": "text", + "required": false, + "title": "Default thinking level" + }, + { + "key": "reasoning", + "kind": "text", + "required": false, + "title": "Reasoning model (true or false)" + }, + { + "key": "max_tokens", + "kind": "text", + "required": false, + "title": "Maximum output tokens" + }, + { + "key": "context_window", + "kind": "text", + "required": false, + "title": "Context window (tokens)" } ], "provider": "custom-inference", @@ -113,6 +137,12 @@ "harnessRequired": false, "image": "ghcr.io/validatedpatterns-sandbox/saw-openclaw@sha256:06eb0e7985ecbd655befa8ce35c8b8e7746c9e609c4e28068403cadd7c956686", "modelInput": "inference.model", + "modelSettingInputs": { + "contextWindow": "inference.context_window", + "maxTokens": "inference.max_tokens", + "reasoning": "inference.reasoning", + "thinking": "inference.thinking" + }, "name": "notebook", "type": "openclaw", "uiRoute": true diff --git a/charts/openshell-rhdh/files/workspace.py b/charts/openshell-rhdh/files/workspace.py index a5703a21..f08edf7b 100644 --- a/charts/openshell-rhdh/files/workspace.py +++ b/charts/openshell-rhdh/files/workspace.py @@ -59,6 +59,10 @@ def sandbox_targets(user, registration, profile, *, model_lifecycle=False): subjectMap="saw-portal-relay-subject" if single else "saw-portal-relay-"+suffix) if model_lifecycle and sb.get("modelInput"): targets[key]["modelInput"] = sb["modelInput"] + # The gate Job publishes these settings with the model, so a + # later change reaches OpenClaw on restart. + if sb.get("modelSettingInputs"): + targets[key]["modelSettingInputs"] = sb["modelSettingInputs"] return targets @@ -87,9 +91,34 @@ def public_model_inputs(profile, secrets): if not re.fullmatch(spelling, value): raise WorkspaceError("invalid public model selector") values[key] = value + # Optional model settings (thinking, reasoning, maxTokens, contextWindow): + # public, noncredential text fields of the same Secret. The runtime + # validates them again when it compiles the workspace. + for _, sb in enabled_catalog_sandboxes(profile): + for setting, key in (sb.get("modelSettingInputs") or {}).items(): + secret, field = key.split(".", 1) + definition = next((f for f in profile["secrets"].get(secret, {}).get("fields", []) + if f["key"] == field and f["kind"] == "text"), None) + pattern = MODEL_SETTING_PATTERNS.get(setting) + if definition is None or pattern is None: + raise WorkspaceError("invalid model setting input") + value = secrets.get(secret, {}).get(field) + if value is None or value == "": + continue + if not isinstance(value, str) or value in confidential or not re.fullmatch(pattern, value.strip()): + raise WorkspaceError(f"invalid {setting} for {key}") + values[key] = value.strip() return values +MODEL_SETTING_PATTERNS = { + "thinking": r"(?i)off|minimal|low|medium|high", + "reasoning": r"(?i)true|false", + "maxTokens": r"[1-9][0-9]{0,8}", + "contextWindow": r"[1-9][0-9]{0,8}", +} + + CUSTOM_INFERENCE_URL = re.compile(r"https://[a-z0-9-]+(?:\.[a-z0-9-]+)+(?::443)?(?:/[A-Za-z0-9_-]+)*/v1") diff --git a/charts/openshell-saw/files/installer/apply_bom.py b/charts/openshell-saw/files/installer/apply_bom.py index 02e1239c..362f571c 100644 --- a/charts/openshell-saw/files/installer/apply_bom.py +++ b/charts/openshell-saw/files/installer/apply_bom.py @@ -650,6 +650,9 @@ def check_trusted_proxy(tp): # mount; how podman reports the mount (see sandbox_harness_mount). The 0.1.x # admission rules above are from the v0.1.2 source. +# The model-entry values SAW replaced, per model, so a setting removed from +# the profile can be restored (ProfileApplier.mark_reasoning_model). +MODEL_SETTINGS_STATE = "/sandbox/.openclaw/saw-model-settings.json" HARNESS_MARKER = ".saw-harness-revision" # written into the volume with the bundle HARNESS_VOLUME_PREFIX = "saw-harness-" HARNESS_VOLUME_LABEL = "saw.redhat.com/harness-volume" @@ -4041,9 +4044,18 @@ def start_openclaw(self, ws, sb, provider): except ValueError as exc: raise InstallerError(f"cannot read OpenClaw managed models: {exc}") from None thinking = (sb.inference_values or {}).get("thinking", "") - if thinking: - self.mark_reasoning_model(exec_cmd, oc_env, provider.type, model_id, - reasoning=thinking != "off") + # An explicit reasoning flag wins (MODEL_REASONING=false keeps a + # thinking default but sends no reasoning_effort); otherwise any + # thinking level but off marks the model as reasoning. + reasoning = (sb.inference_values or {}).get("reasoning") + if reasoning is None and thinking: + reasoning = thinking != "off" + limits = {k: (sb.inference_values or {})[k] for k in MODEL_LIMIT_KEYS + if k in (sb.inference_values or {})} + # Also with nothing to set: a setting removed since the last apply + # restores the model entry's original value (mark_reasoning_model). + self.mark_reasoning_model(exec_cmd, oc_env, provider.type, model_id, + reasoning=reasoning, limits=limits) if (sb.inference_values or {}).get("models") or previous or thinking: current_models = self.cli(*exec_cmd, "sh", "-c", f"{oc_env} openclaw config get agents.defaults --json", @@ -4132,41 +4144,90 @@ def launch_openclaw(self, ws, sb, exec_cmd, oc_env): self.clear_confinement_stop(ws, sb) self.install_keepalive(ws, sb) - def mark_reasoning_model(self, exec_cmd, oc_env, provider_type, model_id, reasoning=True): - """Set whether OpenClaw treats a custom provider's model as reasoning. + def mark_reasoning_model(self, exec_cmd, oc_env, provider_type, model_id, reasoning=True, + limits=None): + """Set whether OpenClaw treats a custom provider's model as reasoning, + and its maxTokens / contextWindow when the profile gives them. OpenClaw knows which of its own models reason; a custom model offers only default and off unless its entry says reasoning: true and lists the efforts the endpoint accepts (sent as reasoning_effort). Thinking - off marks it reasoning: false, so no effort is sent.""" + off (or reasoning: false) marks it reasoning: false, so no effort is + sent. + + Each field SAW sets keeps the value it replaced (MODEL_SETTINGS_STATE), + and a setting the profile no longer gives gets that value back, or is + removed when there was none. OpenClaw's onboarding keeps an existing + model entry's metadata, so without this a cleared setting would stay.""" + desired = dict(limits or {}) + if reasoning is not None: + desired["reasoning"] = reasoning + desired["compat.supportedReasoningEfforts"] = REASONING_EFFORTS if reasoning else None + bare = model_id.removeprefix(f"{provider_type}/") + state_read = self.cli(*exec_cmd, "sh", "-c", + f"if [ -f {MODEL_SETTINGS_STATE} ]; then cat {MODEL_SETTINGS_STATE}; " + "else printf '{}'; fi", check=False, quiet=True) + if self.sh.dry_run: + return + try: + state = json.loads(state_read.out) if state_read.ok else {} + if not isinstance(state, dict): + raise ValueError + except ValueError: + state = {} + originals = state.get(model_id) if isinstance(state.get(model_id), dict) else {} + if not desired and not originals: + return key = f"models.providers.{shlex.quote(provider_type)}.models" found = self.cli(*exec_cmd, "sh", "-c", f"{oc_env} openclaw config get {key} --json", check=False, quiet=True) - if self.sh.dry_run: - return try: models = json.loads(found.out) if found.ok else None except ValueError: models = None - bare = model_id.removeprefix(f"{provider_type}/") entry = next((m for m in models or [] if isinstance(m, dict) and m.get("id") in (bare, model_id)), None) if entry is None: - log(f"WARN: {provider_type} has no model entry for '{bare}'; its thinking level " - "applies only if OpenClaw already treats it as a reasoning model") - return - compat = entry.setdefault("compat", {}) - efforts = REASONING_EFFORTS if reasoning else None - if entry.get("reasoning") is reasoning and compat.get("supportedReasoningEfforts") == efforts: + if desired: + log(f"WARN: {provider_type} has no model entry for '{bare}'; its thinking level " + "and token limits apply only if OpenClaw already has them") return - entry["reasoning"] = reasoning - if reasoning: - compat["supportedReasoningEfforts"] = REASONING_EFFORTS + before = json.dumps(entry, sort_keys=True) + + def get(field): + holder = entry.get("compat", {}) if field.startswith("compat.") else entry + name = field.removeprefix("compat.") + return {"value": holder[name]} if isinstance(holder, dict) and name in holder else {} + + def put(field, saved): + if field.startswith("compat."): + compat = entry.setdefault("compat", {}) + name = field.removeprefix("compat.") + if "value" in saved: + compat[name] = saved["value"] + else: + compat.pop(name, None) + if not compat: + entry.pop("compat") + elif "value" in saved: + entry[field] = saved["value"] + else: + entry.pop(field, None) + + for field in sorted(set(desired) | set(originals)): + if field in desired: + originals.setdefault(field, get(field)) + put(field, {} if desired[field] is None else {"value": desired[field]}) + else: + put(field, originals.pop(field)) + if json.dumps(entry, sort_keys=True) != before: + self.cli(*exec_cmd, "sh", "-c", + f"{oc_env} openclaw config set {key} {shlex.quote(json.dumps(models))}") + if originals: + state[model_id] = originals else: - compat.pop("supportedReasoningEfforts", None) - if not compat: - entry.pop("compat") + state.pop(model_id, None) self.cli(*exec_cmd, "sh", "-c", - f"{oc_env} openclaw config set {key} {shlex.quote(json.dumps(models))}") + f"printf '%s\\n' {shlex.quote(json.dumps(state, sort_keys=True))} > {MODEL_SETTINGS_STATE}") def disable_provider_channels(self, ws, sb, exec_cmd, oc_env): """Keep OpenClaw's own chat channel off for a provider that shares diff --git a/charts/openshell-saw/files/installer/saw_core.py b/charts/openshell-saw/files/installer/saw_core.py index bd5c3dd3..4c70b49f 100644 --- a/charts/openshell-saw/files/installer/saw_core.py +++ b/charts/openshell-saw/files/installer/saw_core.py @@ -200,9 +200,11 @@ class Sandbox: # (the agent, and argv, can read these): those stay on providers. env: dict = field(default_factory=dict) # `inference:` -- how the agent reaches its model: {providerRef, protocol, - # baseUrl?, model, models?, timeoutSeconds?, thinking?}. models maps optional native + # baseUrl?, model, models?, timeoutSeconds?, thinking?, reasoning?, maxTokens?, + # contextWindow?}. models maps optional native # provider names to additional chat model inputs. baseUrl/model/timeoutSeconds - # is a literal or an input ({secretKeyRef: {name, key}, default?, + # and the model settings (thinking, reasoning, maxTokens, contextWindow) + # are each a literal or an input ({secretKeyRef: {name, key}, default?, # required?, title?}); inference_values is it resolved. The installer onboards the # agent from it (by protocol, so any profile-backed provider type works). inference: dict = field(default_factory=dict) @@ -430,9 +432,12 @@ def validate_profile_document(doc, kind, where="profile"): if "protocol" in inference and not isinstance(inference["protocol"], str): raise InstallerError(f"{where}: inference.protocol must be a string") inference = _thinking_off(inference) - if "thinking" in inference and inference["thinking"] not in THINKING_LEVELS: - raise InstallerError(f"{where}: inference.thinking must be one of " - + ", ".join(THINKING_LEVELS)) + for field_name in MODEL_SETTING_KEYS: + if isinstance(inference.get(field_name), dict): + _profile_input(inference[field_name], (str,), where) + elif field_name in inference and model_setting_problem(field_name, inference[field_name]): + raise InstallerError(f"{where}: inference.{field_name} " + + model_setting_problem(field_name, inference[field_name])) for field_name in ("model", "baseUrl", "timeoutSeconds"): kinds = (str, int) if field_name == "timeoutSeconds" else (str,) if field_name in inference: @@ -745,7 +750,51 @@ def _thinking_off(inference): return inference -INFERENCE_KEYS = {"providerRef", "protocol", "baseUrl", "model", "models", "timeoutSeconds", "thinking"} +INFERENCE_KEYS = {"providerRef", "protocol", "baseUrl", "model", "models", "timeoutSeconds", "thinking", + "reasoning", "maxTokens", "contextWindow"} +# The custom model's output and context limits, written to its OpenClaw model +# entry (like NemoClaw's MODEL_MAX_TOKENS and MODEL_CONTEXT_WINDOW). +MODEL_LIMIT_KEYS = ("maxTokens", "contextWindow") +# OpenClaw model settings a profile may give as a literal or as an input +# (usually optional: {secretKeyRef, required: false}); an input that resolves +# to "" leaves the setting unapplied. +MODEL_SETTING_KEYS = ("thinking", "reasoning") + MODEL_LIMIT_KEYS + + +def _positive_int(value): + """An int (or digit string) above zero; YAML booleans are not ints here.""" + if isinstance(value, bool): + return False + if isinstance(value, str): + return value.isdigit() and int(value) > 0 + return isinstance(value, int) and value > 0 + +def model_setting_problem(key, value): + """What is wrong with a literal model setting ("" when fine).""" + if key == "thinking": + return "" if value in THINKING_LEVELS else "must be one of " + ", ".join(THINKING_LEVELS) + if key == "reasoning": + return "" if isinstance(value, bool) else "must be true or false" + return "" if _positive_int(value) else "must be a positive integer" + + +def parse_model_setting(key, text, what): + """A model setting read from a Secret (text) as its typed value.""" + text = text.strip() + if key == "reasoning": + if text.lower() not in ("true", "false"): + raise InstallerError(f"{what} must be true or false") + return text.lower() == "true" + if key == "thinking": + value = text.lower() + else: + value = int(text) if text.isdigit() else text + problem = model_setting_problem(key, value) + if problem: + raise InstallerError(f"{what} {problem}") + return value + + # OpenClaw thinking levels a profile may make the model's default. A level # other than off also marks the model as a reasoning model that accepts # these efforts, which OpenClaw only assumes for its own known models. @@ -977,8 +1026,19 @@ def resolve_inference(ws, sb, read_value, validate_endpoint, forbidden=()): if timeout and (not str(timeout).isdigit() or int(timeout) < 0): raise InstallerError(f"{where}: inference timeoutSeconds must be a non-negative integer") out["timeoutSeconds"] = int(timeout) if timeout else 0 - if spec.get("thinking"): - out["thinking"] = spec["thinking"] + for key in MODEL_SETTING_KEYS: + if key not in spec: + continue + src = spec[key] + if isinstance(src, dict): + text = resolve_bom_input(src, read_value, f"{where}: inference {key}", forbidden) + if text: + out[key] = parse_model_setting(key, text, f"{where}: inference {key}") + elif key == "thinking": + if src: + out[key] = src + else: + out[key] = int(src) if key in MODEL_LIMIT_KEYS else src if "models" in spec: out["models"] = {} for name, src in spec["models"].items(): @@ -1038,11 +1098,17 @@ def sandbox_inference_problems(sb, provider_types, declared_provider_types=None) for key in ("baseUrl", "model"): if key in spec: out += [f"inference {key} {p}" for p in input_problems(spec[key])] - if "thinking" in spec: - if spec["thinking"] not in THINKING_LEVELS: - out.append(f"inference thinking must be one of {', '.join(THINKING_LEVELS)}") + for key in MODEL_SETTING_KEYS: + if key not in spec: + continue + src = spec[key] + problems = ([f"inference {key} {p}" for p in input_problems(src)] if isinstance(src, dict) + else [f"inference {key} {model_setting_problem(key, src)}"] + if model_setting_problem(key, src) else []) + if problems: + out += problems elif sb.type != "openclaw": - out.append("inference thinking is supported only for openclaw sandboxes") + out.append(f"inference {key} is supported only for openclaw sandboxes") models = spec.get("models", {}) if not isinstance(models, dict): out.append("inference models must be a mapping of provider names to model inputs") @@ -1094,7 +1160,7 @@ def profiles_from_plan(data): 'SANDBOX_TYPES', 'BASE_URL_CONFIG_KEYS', 'InstallerError', 'Provider', 'Sandbox', 'Workspace', 'Profile', 'HarnessBundle', 'read_profile_files', '_yaml', 'parse_profiles', 'enabled_workspaces', 'validate_profiles', 'ENV_NAME_RE', 'CREDENTIAL_NAME_RE', 'ENV_VALUE_LIMIT', 'SANDBOX_ENV_KEYS', - 'INPUT_KEYS', 'secret_ref', 'secret_ref_problems', 'INFERENCE_KEYS', 'GATEWAY_SUPERVISOR', 'HOST_AUTOMATIONS_OFF', 'gateway_supervisor_script', 'INFERENCE_PROTOCOLS', 'THINKING_LEVELS', 'REASONING_EFFORTS', + 'INPUT_KEYS', 'secret_ref', 'secret_ref_problems', 'INFERENCE_KEYS', 'MODEL_LIMIT_KEYS', 'MODEL_SETTING_KEYS', 'GATEWAY_SUPERVISOR', 'HOST_AUTOMATIONS_OFF', 'gateway_supervisor_script', 'INFERENCE_PROTOCOLS', 'THINKING_LEVELS', 'REASONING_EFFORTS', 'PROVIDER_PROTOCOLS', 'check_env_value', 'sandbox_env_problems', 'input_problems', 'check_base_url', 'resolve_bom_input', 'resolve_inference', 'inference_protocol', 'sandbox_inference_problems', 'harness_from_plan', 'profiles_from_plan', 'validate_profile_document', 'apply_workspace_sequence', 'select_inference_provider', diff --git a/charts/saw-bom/profiles/custom-inference/default/sandbox.yaml b/charts/saw-bom/profiles/custom-inference/default/sandbox.yaml index 06faad11..fdb3466a 100644 --- a/charts/saw-bom/profiles/custom-inference/default/sandbox.yaml +++ b/charts/saw-bom/profiles/custom-inference/default/sandbox.yaml @@ -31,5 +31,29 @@ spec: title: Model # Self-hosted models can take longer than the agent's default. timeoutSeconds: "300" + # Optional model settings, read from the same `inference` Secret + # (values-secret.yaml). A key that is absent or empty is not applied: + # OpenClaw keeps its own default for that setting. + # The model's default thinking level (off, minimal, low, medium or high; + # a chat's /think overrides it). + thinking: + secretKeyRef: {name: inference, key: thinking} + required: false + title: Default thinking level + # false for a model that is not a reasoning model (MODEL_REASONING=false): + # no reasoning_effort is sent, whatever the thinking level. + reasoning: + secretKeyRef: {name: inference, key: reasoning} + required: false + title: Reasoning model (true or false) + # MODEL_MAX_TOKENS / MODEL_CONTEXT_WINDOW for the model's entry. + maxTokens: + secretKeyRef: {name: inference, key: max_tokens} + required: false + title: Maximum output tokens + contextWindow: + secretKeyRef: {name: inference, key: context_window} + required: false + title: Context window (tokens) ui: route: true diff --git a/charts/saw-portal-container/templates/enrolled-runtime.yaml b/charts/saw-portal-container/templates/enrolled-runtime.yaml index 9f3f77f3..b4f97376 100644 --- a/charts/saw-portal-container/templates/enrolled-runtime.yaml +++ b/charts/saw-portal-container/templates/enrolled-runtime.yaml @@ -62,9 +62,18 @@ subjects: [{kind: ServiceAccount, name: saw-gate-preparation, namespace: {{ $ns {{- $model = required "public model selection missing" (index $site.requestedModels $target.modelInput) }} {{- $job = printf "%s-m%d" $job $publication }} {{- end }} +{{- /* The model's optional settings travel with it, so a changed or cleared +setting reaches OpenClaw on the restart; {} when none is set. */ -}} +{{- $settings := dict }} +{{- if and $model $target.modelSettingInputs }} +{{- range $setting, $input := $target.modelSettingInputs }} +{{- with index ($site.requestedModels | default dict) $input }}{{- $_ := set $settings $setting . }}{{- end }} +{{- end }} +{{- end }} {{- /* Job PodSpecs are immutable. A new artifact or bundle gets a new Job, while an unchanged sync keeps the completed publication. */ -}} {{- $publicationSpec := dict "version" 2 "image" $e.image "owner" $u "subject" $b.ownerSubject "target" $target "gate" $gate "model" $model "generation" $publication -}} +{{- if and $model $target.modelSettingInputs }}{{- $_ := set $publicationSpec "settings" $settings }}{{- end }} {{- $job = printf "%s-%s" $job ($publicationSpec | toJson | sha256sum | trunc 10) }} --- apiVersion: batch/v1 @@ -84,7 +93,7 @@ spec: containers: - name: prep image: {{ $e.image | quote }} - command: [python3, -m, saw_kubernetes.prepare_gate, --owner, {{ $u | quote }}, --subject, {{ $b.ownerSubject | quote }}, --workspace, {{ $target.workspace }}, --sandbox, {{ $target.sandbox }}{{ with $gate.receiptKey }}, --receipt-key, {{ . | quote }}{{ end }}{{ if $target.ui }}, --browser-proof, /proof/relay-proof{{ end }}{{ if $gate.harness }}, --harness, {{ $gate.harness.name | quote }}, {{ $gate.harness.digest | quote }}{{ end }}{{ if $model }}, --model, {{ $model | quote }}, --model-generation, {{ $publication | quote }}{{ end }}] + command: [python3, -m, saw_kubernetes.prepare_gate, --owner, {{ $u | quote }}, --subject, {{ $b.ownerSubject | quote }}, --workspace, {{ $target.workspace }}, --sandbox, {{ $target.sandbox }}{{ with $gate.receiptKey }}, --receipt-key, {{ . | quote }}{{ end }}{{ if $target.ui }}, --browser-proof, /proof/relay-proof{{ end }}{{ if $gate.harness }}, --harness, {{ $gate.harness.name | quote }}, {{ $gate.harness.digest | quote }}{{ end }}{{ if $model }}, --model, {{ $model | quote }}, --model-generation, {{ $publication | quote }}{{ end }}{{ if and $model $target.modelSettingInputs }}, --model-settings, {{ $settings | toJson | quote }}{{ end }}] securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}} volumeMounts: [{name: gate, mountPath: /volume}{{ if $target.ui }}, {name: proof, mountPath: /proof, readOnly: true}{{ end }}{{ if $gate.harness }}, {name: bom, mountPath: /bom, readOnly: true}{{ end }}] volumes: [{name: gate, persistentVolumeClaim: {claimName: {{ $gate.trusted.claimName }}}}{{ if $target.ui }}, {name: proof, secret: {secretName: ui-{{ $target.relayID }}-browser-proof, items: [{key: relay-proof, path: relay-proof}]}}{{ end }}{{ if $gate.harness }}, {name: bom, configMap: {name: saw-bom-profiles}}{{ end }}] diff --git a/charts/saw-users/files/profile-catalog.json b/charts/saw-users/files/profile-catalog.json index e8edccb1..177273d4 100644 --- a/charts/saw-users/files/profile-catalog.json +++ b/charts/saw-users/files/profile-catalog.json @@ -79,6 +79,30 @@ "kind": "text", "required": true, "title": "Model" + }, + { + "key": "thinking", + "kind": "text", + "required": false, + "title": "Default thinking level" + }, + { + "key": "reasoning", + "kind": "text", + "required": false, + "title": "Reasoning model (true or false)" + }, + { + "key": "max_tokens", + "kind": "text", + "required": false, + "title": "Maximum output tokens" + }, + { + "key": "context_window", + "kind": "text", + "required": false, + "title": "Context window (tokens)" } ], "provider": "custom-inference", @@ -113,6 +137,12 @@ "harnessRequired": false, "image": "ghcr.io/validatedpatterns-sandbox/saw-openclaw@sha256:06eb0e7985ecbd655befa8ce35c8b8e7746c9e609c4e28068403cadd7c956686", "modelInput": "inference.model", + "modelSettingInputs": { + "contextWindow": "inference.context_window", + "maxTokens": "inference.max_tokens", + "reasoning": "inference.reasoning", + "thinking": "inference.thinking" + }, "name": "notebook", "type": "openclaw", "uiRoute": true diff --git a/charts/saw-users/files/workspace.py b/charts/saw-users/files/workspace.py index a5703a21..f08edf7b 100644 --- a/charts/saw-users/files/workspace.py +++ b/charts/saw-users/files/workspace.py @@ -59,6 +59,10 @@ def sandbox_targets(user, registration, profile, *, model_lifecycle=False): subjectMap="saw-portal-relay-subject" if single else "saw-portal-relay-"+suffix) if model_lifecycle and sb.get("modelInput"): targets[key]["modelInput"] = sb["modelInput"] + # The gate Job publishes these settings with the model, so a + # later change reaches OpenClaw on restart. + if sb.get("modelSettingInputs"): + targets[key]["modelSettingInputs"] = sb["modelSettingInputs"] return targets @@ -87,9 +91,34 @@ def public_model_inputs(profile, secrets): if not re.fullmatch(spelling, value): raise WorkspaceError("invalid public model selector") values[key] = value + # Optional model settings (thinking, reasoning, maxTokens, contextWindow): + # public, noncredential text fields of the same Secret. The runtime + # validates them again when it compiles the workspace. + for _, sb in enabled_catalog_sandboxes(profile): + for setting, key in (sb.get("modelSettingInputs") or {}).items(): + secret, field = key.split(".", 1) + definition = next((f for f in profile["secrets"].get(secret, {}).get("fields", []) + if f["key"] == field and f["kind"] == "text"), None) + pattern = MODEL_SETTING_PATTERNS.get(setting) + if definition is None or pattern is None: + raise WorkspaceError("invalid model setting input") + value = secrets.get(secret, {}).get(field) + if value is None or value == "": + continue + if not isinstance(value, str) or value in confidential or not re.fullmatch(pattern, value.strip()): + raise WorkspaceError(f"invalid {setting} for {key}") + values[key] = value.strip() return values +MODEL_SETTING_PATTERNS = { + "thinking": r"(?i)off|minimal|low|medium|high", + "reasoning": r"(?i)true|false", + "maxTokens": r"[1-9][0-9]{0,8}", + "contextWindow": r"[1-9][0-9]{0,8}", +} + + CUSTOM_INFERENCE_URL = re.compile(r"https://[a-z0-9-]+(?:\.[a-z0-9-]+)+(?::443)?(?:/[A-Za-z0-9_-]+)*/v1") diff --git a/docs/container-installation.md b/docs/container-installation.md index 1a68ac6d..2df27c44 100644 --- a/docs/container-installation.md +++ b/docs/container-installation.md @@ -18,6 +18,10 @@ owned by the pattern or RHDH. Both VM and container users can coexist in a `saw-users` installation. Each registration has one backend; it is not an in-place VM-to-container migration setting. +Kata workspaces run the same container workspace in a Kata VM, with the same +Kubernetes lifecycle and workspace BOM; for their extra placement steps, follow +the [Kata installation and Developer Hub guide](kata-workspaces.md). + ## Shared platform prerequisites Start with the SAW platform services: Keycloak/owner accounts, governance, @@ -85,8 +89,6 @@ individual workspace must not uninstall this cluster-wide dependency. ## Public inputs and credential references -For Kata workload placement, follow the [Kata installation and Developer Hub guide](kata-workspaces.md). Both modes use the same Kubernetes lifecycle and workspace BOM. - The same site object is used as `containerSites.` for static installs or `portal.containerSites.` for RHDH. It is administrator-owned, not a form field. The component wiring (namespaces, service accounts, SANs, the @@ -127,12 +129,13 @@ owner. The portal Task needs the existing read-only directory client projection ### Prepare large images on cold nodes -The pinned stock OpenShell driver rolls back a sandbox whose bootstrap remains -unfinished for five minutes. A slow first image pull can consume that entire -window. Check cold nodes when qualifying a profile. For large images, install +The stock OpenShell driver rolls back a sandbox whose runtime bootstrap is +still unfinished after `runtime_bootstrap_grace_seconds`, 300 seconds by +default (the SAW gateway chart keeps the default). A slow first image pull can +consume that entire window. Check cold nodes when qualifying a profile. For large images, install the optional `charts/saw-image-cache` chart through the clustergroup before creating workspaces. Give it the same immutable digests selected by the BOM -and site overrides. [Pinned driver](https://github.com/opendatahub-io/openshell/blob/305c8b3d7bbdb97a6f2f7264c3ad43b0087c307f/crates/openshell-driver-kubernetes/src/driver.rs#L284) +and site overrides. [Driver configuration](https://github.com/opendatahub-io/openshell/blob/c2775b8df05619cdd57cb354ea8cd829ec79ee40/crates/openshell-driver-kubernetes/src/config.rs) ```yaml # Site values @@ -760,12 +763,6 @@ python3 scripts/portal-container/check-pod-admission.py \ Each probe must report denial by the workspace Pod policy. An RBAC error, missing API, or collision with an existing Pod fails the check. -The Task reads the Tekton-owned `tekton.dev/pipelineRun` Pod label through the -downward API to identify its credential reservation. If a pending writer disappears, inspect its PipelineRun and the owned -Vault generation before clearing the writer annotation. A missing holder fails -closed. A terminated failed run can be retried for the same registration. - - ### Interrupted creates and updates RHDH reserves the registration before writing credentials. The catalog keeps @@ -776,6 +773,12 @@ project the last committed public configuration. Retry the create form with all required inputs to finish the same registration. Vault writes to multiple secrets are independent; an earlier write may already be visible to ESO. +The portal's registration Task reads the Tekton-owned `tekton.dev/pipelineRun` +Pod label through the downward API to identify its credential reservation. If a +pending writer disappears, inspect its PipelineRun and the owned Vault +generation before clearing the writer annotation. A missing holder fails +closed. A terminated failed run can be retried for the same registration. + The reconciler records the ID from a successful sandbox create before waiting for readiness. It replays an interrupted create with the original request ID on a Running pass. If shutdown encounters an outstanding create with no proven @@ -827,14 +830,15 @@ network and request decisions) over OTLP/gRPC to the collector in The demonstration debug exporter writes complete event bodies, sandbox IDs and trace details to the collector's log, with detailed output and sampling disabled. Pod logs are not durable audit storage; replace the exporter with your SIEM or -log store in `charts/saw-telemetry/values.yaml` for production. W6 inspects the -demo collector's detailed logs and requires a fresh OCSF JSON body whose sandbox -ID matches both the body and the log record's `openshell.sandbox.id` attribute. +log store in `charts/saw-telemetry/values.yaml` for production. The OCSF check +in `make e2e-workspace` (W6) inspects the demo collector's detailed logs and +requires a fresh OCSF JSON body whose sandbox ID matches both the body and the log record's `openshell.sandbox.id` attribute. When using an external exporter, verify records in that backend separately. Set `telemetry.ocsfEndpoint: ""` in `containerDefaults` to turn export off. OpenShell drops events it cannot export, and nothing waits for the collector. -OpenShell 0.1.6 does not export the agent's own tool calls; those are in the -tool gate's log below. +The gateway also relays the agent's own OTLP traces (`telemetry.agentTraces`), +but OpenClaw does not send them yet, so its tool calls appear only in the tool +gate's log below. #### Audit receipts diff --git a/docs/custom-inference.md b/docs/custom-inference.md index 696436dc..23372dbd 100644 --- a/docs/custom-inference.md +++ b/docs/custom-inference.md @@ -153,7 +153,37 @@ stated (`openai`): the installer cannot infer it for a profile of your own. which OpenClaw sends as `reasoning_effort`; the endpoint may ignore it. `off` marks it `reasoning: false` instead (like `MODEL_REASONING=false`); an unquoted YAML `off` (read as `false`) also means off. A - chat's `/think` still overrides the default. VM workspaces only for now. + chat's `/think` still overrides the default. +- `inference.reasoning: false` (like `MODEL_REASONING=false`) marks the model + not reasoning whatever the thinking level, so a level such as `high` stays + its default but no `reasoning_effort` is sent; `true` forces it on. +- `inference.maxTokens` and `inference.contextWindow` (like + `MODEL_MAX_TOKENS` and `MODEL_CONTEXT_WINDOW`) set the model entry's output + and context limits. +- Each of these four settings is a literal or an input. The bundled + custom-inference profile reads them from optional keys of the `inference` + Secret: `thinking`, `reasoning` (`true` or `false`), `max_tokens` and + `context_window`. A key that is absent or empty is not applied, so OpenClaw + keeps its own default; an invalid value fails the apply and names the + setting. A VM reads the Secret at boot, so restart it after changing one. + Removing a key later gives the model entry back the value it had before + SAW set it (or removes the field), so the setting returns to OpenClaw's + default; the replaced values are kept in + `/sandbox/.openclaw/saw-model-settings.json`. +- Container workspaces apply the same settings. As with the model, the + runtime never reads the Secret: the portal copies the four values from the + request into the workspace's public `modelInputs` (`inference.thinking`, + `inference.reasoning`, `inference.max_tokens`, `inference.context_window`), + checking their form, and the runtime validates them again when it compiles + the pod. The OpenClaw config is rewritten at every container start, so a + cleared setting returns to OpenClaw's default. Without any settings the + pod's startup command is unchanged. +- When the owner can change the model later (model lifecycle), the settings + are published with it: the gate preparation Job writes them into the + trusted `model.json` beside the selected model (`{}` when none is set), and + OpenClaw's startup reads them from there. Changing or clearing a setting + restarts the workspace with the new values; the values given at enrollment + are only used to validate the first compile. ### Keycloak compatibility diff --git a/docs/versioned-bom-installer.md b/docs/versioned-bom-installer.md index 6f211d6c..8f92d47d 100644 --- a/docs/versioned-bom-installer.md +++ b/docs/versioned-bom-installer.md @@ -164,7 +164,9 @@ in projected Secrets mounted into the credential proxy. 1. Change `bom:` in the chart values (versions + digests; tags are refused at render time and by the installer). 2. Sync/upgrade the chart. The installer ConfigMap is part of the VM template - checksum, so KubeVirt marks the VM `RestartRequired`. + checksum, so the template no longer matches the running VM. KubeVirt does + not restart it, and may not mark it `RestartRequired`; + `make saw-restart-pending` lists it either way. 3. `virtctl restart ` (or `make saw-restart`). On boot, `saw-install` installs only the changed components. diff --git a/kubernetes-runtime/saw_kubernetes/compiler.py b/kubernetes-runtime/saw_kubernetes/compiler.py index a65e7ee8..4ca7879f 100644 --- a/kubernetes-runtime/saw_kubernetes/compiler.py +++ b/kubernetes-runtime/saw_kubernetes/compiler.py @@ -172,14 +172,79 @@ def compile_profile(profile_dir, config): return compile_profile_files(files, config) +def _model_settings(info): + """The model entry's extra fields and the thinking default, as the VM + installer applies them: an explicit reasoning flag wins; otherwise any + thinking level but off marks the model as reasoning (with the efforts + OpenClaw sends as reasoning_effort).""" + entry = {key: info[key] for key in ("contextWindow", "maxTokens") if key in info} + thinking = info.get("thinking", "") + reasoning = info.get("reasoning") + if reasoning is None and thinking: + reasoning = thinking != "off" + if reasoning is not None: + entry["reasoning"] = reasoning + if reasoning: + entry["compat"] = {"supportedReasoningEfforts": list(shared.REASONING_EFFORTS)} + return entry, thinking + + +# With a mutable model, the settings read from inputs come from the gate's +# model.json with the model, so an owner's later change (or clearing one) +# reaches OpenClaw on restart. The rules are _model_settings's. +PUBLISHED_SETTINGS_JS = """ +if (selection.settings !== undefined && + (typeof selection.settings !== 'object' || selection.settings === null || Array.isArray(selection.settings))) + throw new Error('invalid published model settings'); +const published = (() => { + const settings = Object.assign(@SAW_LITERAL_SETTINGS@, selection.settings ?? {}); + for (const [key, value] of Object.entries(settings)) { + const ok = key === 'thinking' ? @SAW_THINKING_LEVELS@.includes(value) + : key === 'reasoning' ? typeof value === 'boolean' + : (key === 'maxTokens' || key === 'contextWindow') && Number.isSafeInteger(value) && value > 0; + if (!ok) throw new Error('invalid published model settings'); + } + const entry = {}; + for (const key of ['contextWindow', 'maxTokens']) if (key in settings) entry[key] = settings[key]; + const thinking = settings.thinking ?? ''; + const reasoning = settings.reasoning ?? (thinking ? thinking !== 'off' : undefined); + if (reasoning !== undefined) { + entry.reasoning = reasoning; + if (reasoning) entry.compat = {supportedReasoningEfforts: @SAW_REASONING_EFFORTS@}; + } + return {entry, thinking}; +})(); +""" + + +def _published_settings_js(literal): + return (PUBLISHED_SETTINGS_JS + .replace("@SAW_LITERAL_SETTINGS@", json.dumps(literal, sort_keys=True)) + .replace("@SAW_THINKING_LEVELS@", json.dumps(list(shared.THINKING_LEVELS))) + .replace("@SAW_REASONING_EFFORTS@", json.dumps(list(shared.REASONING_EFFORTS)))) + + HOST_AUTOMATIONS_OFF_LINE = "export OPENCLAW_DISABLE_CRON_HOST_EXECUTION=1\n" -def _openclaw_startup(kind, info, host_automations=False): +def _openclaw_startup(kind, info, host_automations=False, published_settings=False): key_env = governed.inference_key_env(kind) endpoint = info.get("baseUrl") or shared.NATIVE_BASE_URLS[kind] provider_id = shared.openclaw_managed_provider_id(kind) timeout = info.get("timeoutSeconds", 0) + if published_settings: + # `published` is defined with the published selection (see compile). + model_entry = "Object.assign({id: model, name: model}, published.entry)" + defaults = ("if (published.thinking) config.agents.defaults.models = " + "{['@SAW_PROVIDER_ID@/' + model]: {params: {thinking: published.thinking}}};\n") + else: + entry, thinking = _model_settings(info) + # Unchanged text when there are no settings, so existing pods keep their command. + model_entry = ("{id: model, name: model}" if not entry else + "Object.assign({id: model, name: model}, " + json.dumps(entry, sort_keys=True) + ")") + defaults = ("" if not thinking else + "config.agents.defaults.models = {['@SAW_PROVIDER_ID@/' + model]: " + "{params: {thinking: " + json.dumps(thinking) + "}}};\n") script = Path(__file__).with_name("openclaw.sh").read_text() if script.count(HOST_AUTOMATIONS_OFF_LINE) != 1: raise ContractError("openclaw.sh must set the host-automation kill switch exactly once") @@ -188,6 +253,8 @@ def _openclaw_startup(kind, info, host_automations=False): script = script.replace(HOST_AUTOMATIONS_OFF_LINE, "# Host-executed automations are enabled by this sandbox's profile.\n") return (script + .replace("@SAW_MODEL_ENTRY@", model_entry) + .replace("@SAW_MODEL_DEFAULTS@\n", defaults) .replace("@SAW_PROVIDER_KEY@", json.dumps(provider_id)) .replace("@SAW_BASE_URL@", json.dumps(endpoint)) .replace("@SAW_TIMEOUT@", f"timeoutSeconds: {timeout}, " if timeout else "") @@ -214,9 +281,20 @@ def _compatible_inference(workspace, sandbox, config): raise ContractError("custom inference endpoint is not approved") from exc inputs = config.get("modelInputs", {}) credentials = {(b["secret"], b["key"]) for b in config.get("credentialBindings", [])} + # The optional model settings (thinking, reasoning, maxTokens, + # contextWindow) this sandbox's profile reads from its inference Secret. + # Like the model, the runtime takes them from public inputs; absent is "". + settings = set() + for name in shared.MODEL_SETTING_KEYS: + src = (sandbox.inference or {}).get(name) + ref = src.get("secretKeyRef") if isinstance(src, dict) else None + if isinstance(ref, dict) and ref.get("name") == provider.credential_secret: + settings.add(ref.get("key")) def read_model(secret, key): if secret != provider.credential_secret or (secret, key) in credentials: raise ContractError("model input is outside the public inference binding") + if key in settings: + return inputs.get(secret + "." + key, "") if custom and key == "url": return endpoint if custom and key != "model": @@ -357,7 +435,14 @@ def compile_profile_files(files, config, gateway_profiles=None): for p in providers): raise ContractError("agent requires an explicitly bound inference credential") kind = inference_provider.type - script = _openclaw_startup(kind, info, sandbox.host_automations) + gate_binding = bindings.get(f"{ws_name}/{sandbox.name}", {}).get("toolGate", {}) + # Settings from inputs: with a mutable model they are published with it. + input_settings = ([k for k in shared.MODEL_SETTING_KEYS + if isinstance((sandbox.inference or {}).get(k), dict)] + if gate_binding.get("modelSelector") is True else []) + literal_settings = {k: info[k] for k in shared.MODEL_SETTING_KEYS + if k in info and k not in input_settings} + script = _openclaw_startup(kind, info, sandbox.host_automations, bool(input_settings)) browser = bindings.get(f"{ws_name}/{sandbox.name}", {}).get("browser") extra = "" if browser is not None: @@ -421,7 +506,7 @@ def compile_profile_files(files, config, gateway_profiles=None): typeof selection.model !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(selection.model)) throw new Error('invalid published model'); const model = selection.model; -""") +""" + (_published_settings_js(literal_settings) if input_settings else "")) if kind in {"custom-inference", "nvidia"}: command[2] = command[2].replace("[A-Za-z0-9._-]{0,99}", r"[A-Za-z0-9._\/-]{0,99}") script = script.replace("for (const path of treeFiles(root).sort()) {", diff --git a/kubernetes-runtime/saw_kubernetes/openclaw.sh b/kubernetes-runtime/saw_kubernetes/openclaw.sh index cd8bae33..8f0d6f76 100644 --- a/kubernetes-runtime/saw_kubernetes/openclaw.sh +++ b/kubernetes-runtime/saw_kubernetes/openclaw.sh @@ -15,11 +15,12 @@ const config = { auth: {mode: 'token', token: crypto.randomBytes(32).toString('hex')}}, models: {providers: {@SAW_PROVIDER_KEY@: {baseUrl: @SAW_BASE_URL@, @SAW_TIMEOUT@api: '@SAW_API@', apiKey: '${@SAW_KEY_ENV@}', - models: [{id: model, name: model}]}}}, + models: [@SAW_MODEL_ENTRY@]}}}, agents: {defaults: {model: {primary: '@SAW_PROVIDER_ID@/' + model}, workspace: '/sandbox/workspace/project'}}, tools: {deny: ['*']} }; +@SAW_MODEL_DEFAULTS@ @SAW_BROWSER_CONFIG@ const target = process.env.OPENCLAW_CONFIG_PATH; // Remove previously managed harness/gate capabilities when absent from this diff --git a/kubernetes-runtime/saw_kubernetes/prepare_gate.py b/kubernetes-runtime/saw_kubernetes/prepare_gate.py index 29530df8..f72e4859 100644 --- a/kubernetes-runtime/saw_kubernetes/prepare_gate.py +++ b/kubernetes-runtime/saw_kubernetes/prepare_gate.py @@ -32,13 +32,14 @@ def verify(directory, files, model_selector=False, browser=False): raise ValueError("existing gate differs from the requested policy or owner") -def publish(root, identity, receipt_key=None, *, model=None, generation=None, browser=False, harness_rules=()): +def publish(root, identity, receipt_key=None, *, model=None, generation=None, browser=False, harness_rules=(), + model_settings=None): assets = Path(shared.__file__).parent files, _, digest, _ = shared.tool_gate_bundle(assets, identity, receipt_key, harness_rules) target = root / "bundle" publish_tree(root, target, files, model_selector=model is not None, browser=browser, replace=True) if model is not None: - publish_model(root, target, model, generation) + publish_model(root, target, model, generation, model_settings) return digest @@ -108,11 +109,35 @@ def publish_harness(root, bom, name, expected_digest): return bundle -def publish_model(root, target, model, generation): - """Fence concurrent or replayed GitOps Jobs on the per-sandbox gate volume.""" +def model_settings(raw): + """The owner's model settings (text from the inference Secret's public + fields) as typed values, checked with the same rules as compilation.""" + if not isinstance(raw, dict) or not set(raw) <= set(shared.MODEL_SETTING_KEYS): + raise ValueError("invalid model settings") + settings = {} + for key, text in raw.items(): + if not isinstance(text, str): + raise ValueError("invalid model settings") + if not text.strip(): + continue + try: + settings[key] = shared.parse_model_setting(key, text, key) + except shared.InstallerError: + raise ValueError("invalid model setting " + key) from None + return settings + + +def publish_model(root, target, model, generation, settings=None): + """Fence concurrent or replayed GitOps Jobs on the per-sandbox gate volume. + + `settings` (a profile that reads model settings) is published with the + model, as {} when none is set, so the startup never falls back to the + values compiled at enrollment.""" if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._/-]{0,99}", model) or type(generation) is not int or generation < 1: raise ValueError("invalid model selection") selected = {"generation":generation, "model":model} + if settings is not None: + selected["settings"] = model_settings(settings) path = target / "model.json" with (root / ".model-lock").open("a") as lock: fcntl.flock(lock, fcntl.LOCK_EX) @@ -121,9 +146,12 @@ def publish_model(root, target, model, generation): if previous["generation"] > generation: return # A newer publication already won. if previous["generation"] == generation: - if previous != selected: + # A publication from before settings were published may gain them. + upgrade = "settings" not in previous and previous == {k: v for k, v in selected.items() if k != "settings"} + if previous != selected and not upgrade: raise ValueError("conflicting model at the same generation") - return + if not upgrade: + return with tempfile.NamedTemporaryFile(dir=root, mode="w", delete=False) as tmp: try: json.dump(selected, tmp) @@ -162,6 +190,7 @@ def publish_browser_proof(directory, proof): parser.add_argument("--browser-proof") parser.add_argument("--model") parser.add_argument("--model-generation",type=int) + parser.add_argument("--model-settings", type=json.loads) receipt = parser.add_mutually_exclusive_group() receipt.add_argument("--receipt-key") receipt.add_argument("--writer-service") @@ -176,7 +205,8 @@ def publish_browser_proof(directory, proof): if args.harness: from .harness import tool_rules rules = tool_rules(publish_harness(Path("/volume"), Path("/bom"), *args.harness)) - result = publish(Path("/volume"), shared.tool_gate_identity(args.owner, args.subject, args.workspace, args.sandbox), args.receipt_key, model=args.model, generation=args.model_generation, browser=bool(args.browser_proof), harness_rules=rules) + result = publish(Path("/volume"), shared.tool_gate_identity(args.owner, args.subject, args.workspace, args.sandbox), args.receipt_key, model=args.model, generation=args.model_generation, browser=bool(args.browser_proof), harness_rules=rules, + model_settings=args.model_settings) if args.browser_proof: publish_browser_proof(Path("/volume/bundle"), Path(args.browser_proof).read_bytes()) print(result) diff --git a/scripts/openshell-saw-restart.sh b/scripts/openshell-saw-restart.sh index 395edc1f..60617bac 100755 --- a/scripts/openshell-saw-restart.sh +++ b/scripts/openshell-saw-restart.sh @@ -21,7 +21,11 @@ if [[ -z "${old_uid}" || "${phase}" != Running ]]; then exit 1 fi -if "${SCRIPT_DIR}/openshell-saw-vm-ssh.sh" 'sudo systemctl poweroff'; then +# --no-block queues the poweroff and returns at once, so the command exits 0 +# before sshd stops. A blocking poweroff races the shutdown: the tunnel drops +# first, and virtctl reports that as exit status 1, the same as a failed +# command, so the restart could not tell the two apart. +if "${SCRIPT_DIR}/openshell-saw-vm-ssh.sh" 'sudo systemctl poweroff --no-block'; then echo "Guest poweroff requested." else ssh_rc=$? diff --git a/scripts/saw-profile-catalog.py b/scripts/saw-profile-catalog.py index 2f0ddac9..53ab2d96 100644 --- a/scripts/saw-profile-catalog.py +++ b/scripts/saw-profile-catalog.py @@ -137,13 +137,17 @@ def secret_ref(src): def sandbox_fields(sandbox, providers=None): """(secret, field) for each input a sandbox reads from a Secret, as the - installer does: its `inference:` settings (baseUrl: a URL field; model and - timeoutSeconds: text). `env:` entries are literals fixed by the profile + installer does: its `inference:` settings (baseUrl: a URL field; model, + timeoutSeconds and the model settings: text). `env:` entries are literals fixed by the profile (a Secret value belongs on a provider) and are not asked for.""" inference = sandbox.get("inference") or {} for key, kind, title in (("baseUrl", "url", "Endpoint base URL"), ("model", "text", "Model"), - ("timeoutSeconds", "text", "Request timeout (seconds)")): + ("timeoutSeconds", "text", "Request timeout (seconds)"), + ("thinking", "text", "Default thinking level"), + ("reasoning", "text", "Reasoning model (true or false)"), + ("maxTokens", "text", "Maximum output tokens"), + ("contextWindow", "text", "Context window (tokens)")): src = inference.get(key) if secret_ref(src): yield secret_ref(src)[0], input_field(src, kind, f"{title} ({sandbox['name']})") @@ -195,6 +199,13 @@ def catalog(): sandboxes[-1]["endpointInput"] = ".".join(endpoint_ref) if model_ref: sandboxes[-1]["modelInput"] = ".".join(model_ref) + # Optional model settings read from the same Secret: public, + # like the model, so a container runtime gets them as inputs. + settings = {key: ".".join(secret_ref(sb["inference"][key])) + for key in ("thinking", "reasoning", "maxTokens", "contextWindow") + if secret_ref((sb.get("inference") or {}).get(key))} + if settings: + sandboxes[-1]["modelSettingInputs"] = settings workspaces.append({"name": name, "description": description, "enabled": enabled, "sandboxes": sandboxes}) if not enabled: diff --git a/scripts/saw-restart-pending.sh b/scripts/saw-restart-pending.sh index 9b5d9846..f35fbbfd 100755 --- a/scripts/saw-restart-pending.sh +++ b/scripts/saw-restart-pending.sh @@ -2,16 +2,30 @@ # Restart the SAW VMs whose spec changed while they were running. # # KubeVirt does not restart a running VM when its template changes (a new -# gateway.toml after switching global.governance.engine, a BOM or profile -# change without vm.liveInputs): it sets the RestartRequired condition and the -# guest keeps its old config until the next boot. This lists those VMs and, -# with CONFIRM=yes, restarts them. Users' running sandboxes stop with the VM. +# gateway.toml after switching global.governance.engine, a BOM change without +# vm.liveInputs): the guest keeps its old config until the next boot. KubeVirt +# sets RestartRequired for some changes but not for the chart's +# openshell.pattern/*-checksum annotations, so a VM is also pending when its +# template's checksums differ from the running instance's. This lists those +# VMs and, with CONFIRM=yes, restarts them. Users' running sandboxes stop with +# the VM. set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" vms="$(oc get vm -A -l openshell.pattern/role=gateway -o json)" -pending="$(jq -r '.items[] - | select(any(.status.conditions[]?; .type == "RestartRequired" and .status == "True")) +vmis="$(oc get vmi -A -l openshell.pattern/role=gateway -o json)" +# The VMI list goes in through a file, not argv: with tens of VMs it exceeds +# the per-argument limit (Argument list too long). +pending="$(jq -r --slurpfile vmis <(printf '%s' "${vmis}") ' + def checksums: (.metadata.annotations // {}) + | with_entries(select(.key | startswith("openshell.pattern/") and endswith("-checksum"))); + ($vmis[0].items | map({key: "\(.metadata.namespace)/\(.metadata.name)", value: checksums}) + | from_entries) as $running + | .items[] + | $running["\(.metadata.namespace)/\(.metadata.name)"] as $booted + | ((.spec.template // {}) | checksums) as $wanted + | select(any(.status.conditions[]?; .type == "RestartRequired" and .status == "True") + or ($booted != null and $wanted != {} and $wanted != $booted)) | [.metadata.namespace, .metadata.name] | @tsv' <<<"${vms}")" if [[ -z "${pending}" ]]; then @@ -19,7 +33,7 @@ if [[ -z "${pending}" ]]; then exit 0 fi -echo "SAW VMs waiting for a restart (RestartRequired):" +echo "SAW VMs waiting for a restart:" while IFS=$'\t' read -r ns name; do printf ' %-20s %s\n' "${name}" "${ns}" done <<<"${pending}" diff --git a/tests/charts/test_portal_container.py b/tests/charts/test_portal_container.py index c306adf7..4900a03a 100644 --- a/tests/charts/test_portal_container.py +++ b/tests/charts/test_portal_container.py @@ -715,3 +715,45 @@ def test_the_pattern_installs_the_collector(): for signal in ("logs", "traces"): # OCSF events and relayed agent traces assert pipelines[signal]["receivers"] == ["otlp"] and pipelines[signal]["exporters"] == ["debug"] assert collector["spec"]["config"]["receivers"]["otlp"]["protocols"] == {"grpc": {"endpoint": "0.0.0.0:4317"}} + + +SETTING_INPUTS = {"thinking": "inference.thinking", "maxTokens": "inference.max_tokens"} + + +def gate_publication(requested, restart): + """The gate Job for a lifecycle workspace whose profile reads model settings.""" + site = copy.deepcopy(SITE) + site["targets"]["default/notebook"].update(modelInput="inference.model", modelSettingInputs=SETTING_INPUTS) + site.update(lifecycleVersion=1, restartGeneration=restart, requestedModels=requested) + site["enrollment"] = dict( + registration=REG, image="ghcr.io/example/saw-kubernetes-runtime@sha256:" + "b" * 64, revision="1" * 40, + approved={}, intent={"profileRef": {"name": "saw-bom-profiles"}, "bindings": { + "ownerID": user()["installationID"], "ownerSubject": SITE["subject"], + "namespace": "saw-" + U, "namespaceUID": "fixture-uid", "mode": "container", + "bindings": {"default/notebook": { + "workspace": {"claimName": "workspace-" + U}, + "toolGate": {"trusted": {"claimName": "saw-gate-" + U}, + "audit": {"claimName": "saw-audit-" + U}, + "ownerLogin": U, "receiptKey": "fixture-public-key", "modelSelector": True}, + "browser": {"ownerLogin": U, "origin": "https://alice-default-notebook-ui.apps.cluster.example.com"}}}}}) + resources = render("saw-portal-container", U, "saw-" + U, dict( + site=site, owner=U, ownerSubject=SITE["subject"], registration=REG, + installationID=user()["installationID"], intentGeneration=1, + vaultPrefix=user()["vaultPrefix"], **{"global": GLOBAL})) + job, = [r for r in resources if r["kind"] == "Job" and r["metadata"]["name"].startswith("saw-gate-preparation")] + command = job["spec"]["template"]["spec"]["containers"][0]["command"] + settings = json.loads(command[command.index("--model-settings") + 1]) + return job["metadata"]["name"], command[command.index("--model") + 1], settings + + +def test_gate_job_publishes_changed_and_cleared_model_settings(): + """create -> update -> clear: each restart's Job carries the current settings.""" + created = gate_publication({"inference.model": "org/model", "inference.thinking": "high", + "inference.max_tokens": "32768"}, 0) + assert created[1:] == ("org/model", {"thinking": "high", "maxTokens": "32768"}) + updated = gate_publication({"inference.model": "org/model", "inference.thinking": "high", + "inference.max_tokens": "16384"}, 2) + assert updated[1:] == ("org/model", {"thinking": "high", "maxTokens": "16384"}) + cleared = gate_publication({"inference.model": "org/model"}, 3) + assert cleared[1:] == ("org/model", {}) + assert len({created[0], updated[0], cleared[0]}) == 3, "each publication is a new Job" diff --git a/tests/installer/fakes/openshell b/tests/installer/fakes/openshell index f85d92a2..7cd59b57 100755 --- a/tests/installer/fakes/openshell +++ b/tests/installer/fakes/openshell @@ -551,6 +551,14 @@ elif op == "sandbox exec": if script.startswith("if [ -f /sandbox/.openclaw/saw-models.json ]"): print(sb.get("files", {}).get(".openclaw/saw-models.json", "[]")) sys.exit(0) + if script.startswith("if [ -f /sandbox/.openclaw/saw-model-settings.json ]"): + print(sb.get("files", {}).get(".openclaw/saw-model-settings.json", "{}")) + sys.exit(0) + settings_record = re.fullmatch(r"printf '%s\\n' (.*) > /sandbox/.openclaw/saw-model-settings.json", script) + if settings_record: + sb.setdefault("files", {})[".openclaw/saw-model-settings.json"] = shlex.split(settings_record.group(1))[0] + save() + sys.exit(0) if 'const file = "/sandbox/.openclaw/openclaw.json"' in script: cfg = sb.setdefault("openclawConfig", {}) paths = cfg.get("plugins.load.paths") or [] diff --git a/tests/installer/test_custom_endpoint.py b/tests/installer/test_custom_endpoint.py index b139c635..78e74260 100644 --- a/tests/installer/test_custom_endpoint.py +++ b/tests/installer/test_custom_endpoint.py @@ -19,6 +19,9 @@ MODEL = "meta-llama/Llama-3.1-8B-Instruct" ROOT = Path(__file__).resolve().parents[2] EXTRA_PROFILE = ROOT / "overrides/governance-profiles/custom-inference.yaml" +# The optional model settings, as the inference Secret carries them. +MODEL_SETTINGS = {"thinking": "high", "reasoning": "false", "max_tokens": "32768", + "context_window": "128000"} DEFAULT_CATALOG = {"web-search": ["api.tavily.com", "api.search.brave.com", "registry.npmjs.org"], "brave": ["api.search.brave.com"], "nvidia": ["integrate.api.nvidia.com"]} @@ -36,7 +39,7 @@ def governed_catalog(fake_env): def custom_secrets(secrets_dir): inference = secrets_dir / "inference" for key, value in {"provider": "custom-inference", - "url": URL + "/", "model": MODEL}.items(): + "url": URL + "/", "model": MODEL, **MODEL_SETTINGS}.items(): (inference / key).write_text(value + "\n") return secrets_dir @@ -64,7 +67,9 @@ def test_profile_is_valid_and_reads_url_and_model_from_the_secret(ab, profiles, # ...the endpoint and model are the sandbox's (the URL normalised). sb = notebook(profiles) assert sb.inference_values == {"providerRef": "custom-inference", "protocol": "openai", - "baseUrl": URL, "model": MODEL, "timeoutSeconds": 300} + "baseUrl": URL, "model": MODEL, "timeoutSeconds": 300, + "thinking": "high", "reasoning": False, + "maxTokens": 32768, "contextWindow": 128000} assert (ab.sandbox_endpoint(sb, custom), ab.sandbox_model(sb, custom)) == (URL, MODEL) @@ -391,6 +396,8 @@ def test_a_thinking_level_marks_the_model_as_reasoning_and_sets_its_default( """OpenClaw offers only default/off for a custom model unless its entry says reasoning: true and lists the efforts; the level is then the model's default (a chat's /think still overrides it).""" + for key in ("reasoning", "maxTokens", "contextWindow"): + notebook(profiles).inference.pop(key, None) notebook(profiles).inference["thinking"] = "medium" creds = resolve(ab, profiles, custom_secrets) ab.ProfileApplier(ab.Shell(), config, creds).apply(profiles) @@ -422,6 +429,87 @@ def test_a_thinking_level_marks_the_model_as_reasoning_and_sets_its_default( "agents.defaults.models"][model_id] == {} +def test_reasoning_false_keeps_the_thinking_default_and_sets_the_token_limits( + ab, fake_env, config, profiles, custom_secrets, governed_catalog): + """MODEL_REASONING=false with a thinking level: the level stays the + model's default but no reasoning_effort is sent; maxTokens and + contextWindow land on the model's entry.""" + creds = resolve(ab, profiles, custom_secrets) + ab.ProfileApplier(ab.Shell(), config, creds).apply(profiles) + state = fake_env.openshell_state() + sb = state["sandboxes"]["default/notebook"] + sb["openclawConfig"]["models.providers.custom-inference.models"] = [ + {"id": MODEL, "name": MODEL, "contextWindow": 200000, "reasoning": True, + "compat": {"supportedReasoningEfforts": ["low", "medium", "high"]}}] + fake_env.set_openshell_state(state) + ab.ProfileApplier(ab.Shell(), config, creds).apply(profiles) + cfg = fake_env.openshell_state()["sandboxes"]["default/notebook"]["openclawConfig"] + assert cfg["models.providers.custom-inference.models"] == [ + {"id": MODEL, "name": MODEL, "contextWindow": 128000, "maxTokens": 32768, "reasoning": False}] + assert cfg["agents.defaults.models"][f"custom-inference/{MODEL}"] == {"params": {"thinking": "high"}} + + +def test_cleared_settings_restore_the_model_entry( + ab, fake_env, config, custom_secrets, governed_catalog): + """Set, clear, reapply: a setting removed from the Secret gives the model + entry its original value back (or removes a field it did not have), and + a later apply leaves it alone. OpenClaw's onboarding keeps existing model + metadata, so the installer has to undo its own overrides.""" + original = {"id": MODEL, "name": MODEL, "contextWindow": 200000, "reasoning": True, + "compat": {"supportedReasoningEfforts": ["low", "medium", "high"]}} + + def apply(): + profiles = ab.parse_profiles(profile_files("custom-inference")) + ab.ProfileApplier(ab.Shell(), config, resolve(ab, profiles, custom_secrets)).apply(profiles) + return fake_env.openshell_state()["sandboxes"]["default/notebook"] + + apply() + state = fake_env.openshell_state() + state["sandboxes"]["default/notebook"]["openclawConfig"][ + "models.providers.custom-inference.models"] = [dict(original), {"id": "other"}] + fake_env.set_openshell_state(state) + sb = apply() + assert sb["openclawConfig"]["models.providers.custom-inference.models"][0] == { + "id": MODEL, "name": MODEL, "contextWindow": 128000, "maxTokens": 32768, "reasoning": False} + + for key in ("thinking", "reasoning", "max_tokens", "context_window"): + (custom_secrets / "inference" / key).unlink() + sb = apply() + cfg = sb["openclawConfig"] + assert cfg["models.providers.custom-inference.models"] == [original, {"id": "other"}] + assert cfg["agents.defaults.models"][f"custom-inference/{MODEL}"] == {} + assert json.loads(sb["files"][".openclaw/saw-model-settings.json"]) == {} + assert apply()["openclawConfig"]["models.providers.custom-inference.models"] == [original, {"id": "other"}] + + +def test_clearing_one_setting_keeps_the_others(ab, fake_env, config, custom_secrets, governed_catalog): + """Only the removed setting is restored; a field the model entry did not + have before is removed rather than left at the old override.""" + def apply(): + profiles = ab.parse_profiles(profile_files("custom-inference")) + ab.ProfileApplier(ab.Shell(), config, resolve(ab, profiles, custom_secrets)).apply(profiles) + return fake_env.openshell_state()["sandboxes"]["default/notebook"]["openclawConfig"] + + apply() + state = fake_env.openshell_state() + state["sandboxes"]["default/notebook"]["openclawConfig"][ + "models.providers.custom-inference.models"] = [{"id": MODEL, "name": MODEL}] + fake_env.set_openshell_state(state) + assert apply()["models.providers.custom-inference.models"] == [ + {"id": MODEL, "name": MODEL, "contextWindow": 128000, "maxTokens": 32768, "reasoning": False}] + (custom_secrets / "inference" / "max_tokens").unlink() + assert apply()["models.providers.custom-inference.models"] == [ + {"id": MODEL, "name": MODEL, "contextWindow": 128000, "reasoning": False}] + + +@pytest.mark.parametrize("key,value", [("reasoning", "no"), ("maxTokens", 0), + ("contextWindow", "big"), ("maxTokens", True)]) +def test_bad_reasoning_or_token_limits_are_refused(ab, profiles, key, value): + sb = notebook(profiles) + sb.inference[key] = value + assert ab.sandbox_inference_problems(sb, {"custom-inference": "custom-inference"}) + + @pytest.mark.parametrize("level", ["max", "Medium", 1]) def test_an_unknown_thinking_level_is_refused(ab, profiles, level): sb = notebook(profiles) @@ -433,5 +521,39 @@ def test_an_unquoted_yaml_off_means_off(ab): """YAML 1.1 reads `thinking: off` as false; it still means off.""" files = profile_files("custom-inference") key = next(k for k in files if k.endswith("__sandbox.yaml")) - files[key] = files[key].replace('timeoutSeconds: "300"', 'timeoutSeconds: "300"\n thinking: off') + doc = yaml.safe_load(files[key]) + doc["spec"]["sandboxes"][0]["inference"]["thinking"] = "off" + files[key] = yaml.safe_dump(doc).replace("thinking: 'off'", "thinking: off") assert notebook(ab.parse_profiles(files)).inference["thinking"] == "off" + + +def test_model_settings_left_out_of_the_secret_are_not_applied(ab, profiles, custom_secrets): + """The settings are optional Secret inputs: an absent or empty key leaves + the setting out, so OpenClaw keeps its own default.""" + (custom_secrets / "inference" / "thinking").unlink() + (custom_secrets / "inference" / "max_tokens").write_text("\n") + resolve(ab, profiles, custom_secrets) + values = notebook(profiles).inference_values + assert "thinking" not in values and "maxTokens" not in values + assert (values["reasoning"], values["contextWindow"]) == (False, 128000) + for key in ("reasoning", "context_window"): + (custom_secrets / "inference" / key).unlink() + profiles2 = ab.parse_profiles(profile_files("custom-inference")) + resolve(ab, profiles2, custom_secrets) + assert not set(ab.MODEL_SETTING_KEYS) & set(notebook(profiles2).inference_values) + + +@pytest.mark.parametrize("key,value", [("thinking", "max"), ("reasoning", "no"), + ("max_tokens", "0"), ("context_window", "big")]) +def test_bad_model_settings_in_the_secret_are_refused(ab, profiles, custom_secrets, key, value): + (custom_secrets / "inference" / key).write_text(value + "\n") + with pytest.raises(ab.InstallerError, match="inference"): + resolve(ab, profiles, custom_secrets) + + +def test_the_secret_settings_are_optional_form_fields(ab, profiles): + """Shipped as inputs, not literals: valid, and not required.""" + spec = notebook(profiles).inference + for key in ab.MODEL_SETTING_KEYS: + assert spec[key]["required"] is False + assert not ab.sandbox_inference_problems(notebook(profiles), {"custom-inference": "custom-inference"}) diff --git a/tests/installer/test_review_135.py b/tests/installer/test_review_135.py index 38a7a5f1..e7125b0b 100644 --- a/tests/installer/test_review_135.py +++ b/tests/installer/test_review_135.py @@ -859,7 +859,11 @@ def test_the_shipped_form_fields_match_the_profiles(): cat = json.loads((ROOT / "charts" / "openshell-rhdh" / "files" / "profile-catalog.json").read_text())["profiles"] custom = {f["key"]: f for f in cat["custom-inference"]["secrets"]["inference"]["fields"]} - assert set(custom) == {"api_key", "url", "model"} + assert set(custom) == {"api_key", "url", "model", "thinking", "reasoning", "max_tokens", + "context_window"} + # The model settings are optional: absent, OpenClaw keeps its default. + assert not any(custom[k]["required"] for k in ("thinking", "reasoning", "max_tokens", + "context_window")) assert custom["url"]["kind"] == "url" and custom["url"]["required"] ds = {f["key"]: f for f in cat["data-science"]["secrets"]["inference"]["fields"]} # One model field per sandbox: selections are not coupled. diff --git a/tests/kubernetes_runtime/test_model_selection.py b/tests/kubernetes_runtime/test_model_selection.py index a64ec2be..b2b4e519 100644 --- a/tests/kubernetes_runtime/test_model_selection.py +++ b/tests/kubernetes_runtime/test_model_selection.py @@ -19,3 +19,39 @@ def test_publication_fences_stale_and_conflicting_jobs(tmp_path): (bundle / "unexpected").touch() with pytest.raises(ValueError): verify(bundle, {}, model_selector=True) + + +def test_settings_are_published_with_the_model_and_can_be_cleared(tmp_path): + """create -> update -> clear, as the gate Jobs of successive restarts.""" + bundle = tmp_path / "bundle" + bundle.mkdir() + published = lambda: json.loads((bundle / "model.json").read_text()) + publish_model(tmp_path, bundle, "org/model", 1, {"thinking": "High", "maxTokens": "32768", "reasoning": ""}) + assert published() == {"generation": 1, "model": "org/model", + "settings": {"thinking": "high", "maxTokens": 32768}} + publish_model(tmp_path, bundle, "org/model", 2, {"thinking": "high", "maxTokens": "16384"}) + assert published()["settings"] == {"thinking": "high", "maxTokens": 16384} + publish_model(tmp_path, bundle, "org/model", 3, {}) + assert published() == {"generation": 3, "model": "org/model", "settings": {}} + verify(bundle, {}, model_selector=True) + + +def test_a_publication_from_before_settings_gains_them_at_the_same_generation(tmp_path): + bundle = tmp_path / "bundle" + bundle.mkdir() + publish_model(tmp_path, bundle, "org/model", 1) + publish_model(tmp_path, bundle, "org/model", 1, {"maxTokens": "8192"}) + assert json.loads((bundle / "model.json").read_text())["settings"] == {"maxTokens": 8192} + with pytest.raises(ValueError, match="conflicting"): + publish_model(tmp_path, bundle, "org/model", 1, {"maxTokens": "4096"}) + + +@pytest.mark.parametrize("settings", [{"thinking": "max"}, {"reasoning": "yes"}, {"maxTokens": "0"}, + {"contextWindow": "$(id)"}, {"temperature": "1"}, ["thinking"], + {"maxTokens": 12}]) +def test_invalid_settings_are_not_published(tmp_path, settings): + bundle = tmp_path / "bundle" + bundle.mkdir() + with pytest.raises(ValueError, match="invalid"): + publish_model(tmp_path, bundle, "org/model", 1, settings) + assert not (bundle / "model.json").exists() diff --git a/tests/kubernetes_runtime/test_model_settings.py b/tests/kubernetes_runtime/test_model_settings.py new file mode 100644 index 00000000..c252d8e9 --- /dev/null +++ b/tests/kubernetes_runtime/test_model_settings.py @@ -0,0 +1,158 @@ +"""Container workspaces apply the custom model's optional settings (thinking, +reasoning, maxTokens, contextWindow) the way the VM installer does. + +Like the model, the runtime reads them from the workspace's public +modelInputs, never from the Secret. Unset settings leave the compiled startup +command exactly as before, so existing pods are not recreated. +""" +import json +import shutil +import subprocess + +import pytest + +from saw_kubernetes.compiler import ContractError, compile_profile +from .test_openclaw import agent +from .test_runtime import sandbox, source # noqa: F401 (fixture) + +SETTINGS = {"thinking": "thinking", "reasoning": "reasoning", + "maxTokens": "max_tokens", "contextWindow": "context_window"} + + +def declare_settings(source): + """The shipped custom-inference profile's optional inputs.""" + sandbox(source, lambda s: s["inference"].update({ + name: {"secretKeyRef": {"name": "inference", "key": key}, "required": False} + for name, key in SETTINGS.items()})) + + +def compiled(source, **inputs): + source[1].setdefault("modelInputs", {}).update( + {f"inference.{SETTINGS[name]}": value for name, value in inputs.items()}) + return compile_profile(*source)["workspaces"][0]["sandboxes"][0]["spec"]["command"] + + +def openclaw_config(command): + """Run the startup script's config builder (the JS before it writes).""" + if not shutil.which("node"): + pytest.skip("node is required to execute the compiled startup") + js = command[2].split("<<'JS'\n", 1)[1].split("\nJS\n", 1)[0] + js = js.split("const target = process.env.OPENCLAW_CONFIG_PATH;", 1)[0] + # As the startup runs it: `node - "$1"` (the model is process.argv[2]). + done = subprocess.run(["node", "-", command[-1]], input=js + "\nconsole.log(JSON.stringify(config));", + capture_output=True, text=True) + assert done.returncode == 0, done.stderr + return json.loads(done.stdout) + + +def model_entry(config): + (provider,) = config["models"]["providers"].values() + (entry,) = provider["models"] + return entry + + +def test_no_settings_leaves_the_startup_command_unchanged(source): + agent(source, "custom-inference", "org/model") + before = compiled(source) + declare_settings(source) + assert compiled(source) == before, "declared but unset settings must not change the pod" + config = openclaw_config(before) + assert model_entry(config) == {"id": "org/model", "name": "org/model"} + assert "models" not in config["agents"]["defaults"] + + +def test_settings_reach_the_model_entry_and_thinking_default(source): + agent(source, "custom-inference", "org/model") + declare_settings(source) + config = openclaw_config(compiled(source, thinking="high", reasoning="false", + maxTokens="32768", contextWindow="128000")) + assert model_entry(config) == {"id": "org/model", "name": "org/model", "maxTokens": 32768, + "contextWindow": 128000, "reasoning": False} + (selected, choice), = config["agents"]["defaults"]["models"].items() + assert selected.endswith("/org/model") and selected == config["agents"]["defaults"]["model"]["primary"] + assert choice == {"params": {"thinking": "high"}} + + +def test_a_thinking_level_alone_marks_the_model_reasoning(source): + """As on the VM: no explicit reasoning flag, a level other than off.""" + agent(source, "custom-inference", "org/model") + declare_settings(source) + entry = model_entry(openclaw_config(compiled(source, thinking="Medium"))) + assert entry["reasoning"] is True + assert entry["compat"] == {"supportedReasoningEfforts": ["low", "medium", "high"]} + entry = model_entry(openclaw_config(compiled(source, thinking="off"))) + assert entry["reasoning"] is False and "compat" not in entry + + +@pytest.mark.parametrize("name,value", [("thinking", "max"), ("reasoning", "yes"), ("maxTokens", "0"), + ("contextWindow", "big"), ("maxTokens", "$(id)")]) +def test_invalid_settings_are_refused(source, name, value): + agent(source, "custom-inference", "org/model") + declare_settings(source) + with pytest.raises(ContractError): + compiled(source, **{name: value}) + + +def test_only_declared_settings_are_read(source): + """A modelInputs key the profile does not reference is ignored.""" + agent(source, "custom-inference", "org/model") + before = compiled(source) + assert compiled(source, thinking="high") == before + + +def mutable(source): + """A lifecycle workspace: the model (and its settings) come from the gate.""" + import base64 + key = base64.b64encode(bytes.fromhex("302a300506032b6570032100") + bytes(range(32))).decode() + source[1]["bindings"]["default/toolbox"]["toolGate"] = { + "ownerLogin": "alice", "receiptKey": key, "modelSelector": True, + "trusted": {"claimName": "saw-gate-test", "uid": "gate-uid", "readOnly": True}, + "audit": {"claimName": "saw-audit-test", "uid": "audit-uid", "readOnly": False}} + + +def config_from_gate(command, selection): + """Run the startup's config builder with `selection` as the gate's model.json.""" + if not shutil.which("node"): + pytest.skip("node is required to execute the compiled startup") + js = command[2].split("<<'JS'\n", 1)[1].split("\nJS\n", 1)[0] + js = js.split("const target = process.env.OPENCLAW_CONFIG_PATH;", 1)[0] + js = js.split("// Best-effort audit", 1)[0].split("const root =", 1)[0] # stop before the gate preflight + js = js.replace("fs.readFileSync('/sandbox/.saw/trusted/model.json','utf8')", json.dumps(json.dumps(selection))) + done = subprocess.run(["node", "-"], input=js + "\nconsole.log(JSON.stringify(config));", + capture_output=True, text=True) + return done.returncode, (json.loads(done.stdout) if done.returncode == 0 else done.stderr) + + +def test_mutable_model_settings_follow_each_publication(source): + """create -> update -> clear: the compiled command is stable (it holds the + enrollment-time values only for validation) and OpenClaw gets the settings + published with the current selection.""" + agent(source, "custom-inference", "org/model") + declare_settings(source) + mutable(source) + command = compiled(source, thinking="high", maxTokens="32768") + selections = [{"thinking": "high", "maxTokens": 32768}, {"thinking": "high", "maxTokens": 16384}, {}] + entries = [] + for generation, settings in enumerate(selections, 1): + code, config = config_from_gate(command, {"generation": generation, "model": "org/model", + "settings": settings}) + assert code == 0, config + entries.append((model_entry(config), config["agents"]["defaults"].get("models"))) + assert entries[0][0]["maxTokens"] == 32768 and entries[0][0]["reasoning"] is True + assert entries[1][0]["maxTokens"] == 16384 + assert list(entries[1][1].values()) == [{"params": {"thinking": "high"}}] + assert entries[2] == ({"id": "org/model", "name": "org/model"}, None), "cleared settings use the defaults" + + +def test_mutable_model_keeps_literal_settings_and_rejects_bad_publications(source): + agent(source, "custom-inference", "org/model") + declare_settings(source) + sandbox(source, lambda s: s["inference"].update(contextWindow=128000)) + mutable(source) + command = compiled(source) + code, config = config_from_gate(command, {"generation": 1, "model": "org/model", "settings": {"reasoning": False}}) + assert code == 0, config + assert model_entry(config) == {"id": "org/model", "name": "org/model", "contextWindow": 128000, "reasoning": False} + for bad in [{"thinking": "max"}, {"maxTokens": "16384"}, {"maxTokens": 0}, {"temperature": 1}, []]: + code, _ = config_from_gate(command, {"generation": 1, "model": "org/model", "settings": bad}) + assert code != 0, bad diff --git a/tests/portal/test_portal.py b/tests/portal/test_portal.py index 4031cf82..c5ae4152 100644 --- a/tests/portal/test_portal.py +++ b/tests/portal/test_portal.py @@ -2311,6 +2311,34 @@ def test_public_nvidia_selector_uses_its_catalog_field(portal, field): portal.public_model_inputs(profile, inputs) +def test_custom_inference_model_settings_become_public_inputs(portal): + """The custom-inference profile's optional model settings reach a + container runtime as public inputs, like the model; empty ones do not.""" + catalog = json.loads((PORTAL.parent / "profile-catalog.json").read_text()) + profile = catalog["profiles"]["custom-inference"] + (sb,) = [sb for ws in profile["workspaces"] for sb in ws["sandboxes"] if sb.get("endpointInput")] + assert sb["modelSettingInputs"] == {"thinking": "inference.thinking", "reasoning": "inference.reasoning", + "maxTokens": "inference.max_tokens", + "contextWindow": "inference.context_window"} + inputs = {"inference": {"api_key": "private-test-key", "url": "https://models.example.test/v1", + "model": "org/model", "thinking": "high", "reasoning": "false", + "max_tokens": "32768", "context_window": ""}} + assert portal.public_model_inputs(profile, inputs) == { + "inference.model": "org/model", "inference.thinking": "high", + "inference.reasoning": "false", "inference.max_tokens": "32768"} + + +@pytest.mark.parametrize("field,value", [("thinking", "max"), ("reasoning", "yes"), ("max_tokens", "0"), + ("context_window", "1e6"), ("max_tokens", "$(id)"), + ("thinking", "private-test-key")]) +def test_custom_inference_model_settings_are_validated(portal, field, value): + catalog = json.loads((PORTAL.parent / "profile-catalog.json").read_text()) + profile = catalog["profiles"]["custom-inference"] + inputs = {"inference": {"api_key": "private-test-key", "model": "org/model", field: value}} + with pytest.raises(portal.PortalError, match="invalid "): + portal.public_model_inputs(profile, inputs) + + def test_owner_state_change_is_generation_scoped_and_does_not_touch_vault(portal, world, monkeypatch): fake, signer = world site = synthetic_preflight_site(portal, { diff --git a/tests/scripts/test_make_interface.py b/tests/scripts/test_make_interface.py index 8407d804..b4b48a5f 100644 --- a/tests/scripts/test_make_interface.py +++ b/tests/scripts/test_make_interface.py @@ -693,11 +693,13 @@ def test_discovery_log_error_does_not_hide_build_phase(tmp_path, terminal): assert not any("imageDigest" in line for line in calls) -def fake_cluster(tmp_path, vms): +def fake_cluster(tmp_path, vms, vmis='{"items": []}'): bin_dir = tmp_path / "bin" bin_dir.mkdir() (tmp_path / "vms.json").write_text(vms) - executable(bin_dir / "oc", f'cat "{tmp_path}/vms.json"\n') + (tmp_path / "vmis.json").write_text(vmis) + executable(bin_dir / "oc", f'case " $* " in *" vmi "*) cat "{tmp_path}/vmis.json";; ' + f'*) cat "{tmp_path}/vms.json";; esac\n') executable(bin_dir / "virtctl", f'echo "$*" >> "{tmp_path}/restarted"\n') return dict(os.environ, PATH=f"{bin_dir}:{os.environ['PATH']}") @@ -735,6 +737,39 @@ def test_saw_restart_pending_restarts_only_pending_vms(tmp_path): assert (tmp_path / "restarted").read_text() == "saw-alice alice\n" +CHECKSUM_VMS = """{"items": [ + {"metadata": {"name": "alice", "namespace": "saw-alice"}, + "spec": {"template": {"metadata": {"annotations": { + "openshell.pattern/installer-checksum": "new", "openshell.pattern/cloudinit-checksum": "c1"}}}}, + "status": {"conditions": [{"type": "Ready", "status": "True"}]}}, + {"metadata": {"name": "bob", "namespace": "saw-bob"}, + "spec": {"template": {"metadata": {"annotations": { + "openshell.pattern/installer-checksum": "same", "openshell.pattern/cloudinit-checksum": "c1"}}}}, + "status": {"conditions": [{"type": "Ready", "status": "True"}]}}, + {"metadata": {"name": "carol", "namespace": "saw-carol"}, + "spec": {"template": {"metadata": {"annotations": { + "openshell.pattern/installer-checksum": "new"}}}}, + "status": {"conditions": []}} +]}""" + +CHECKSUM_VMIS = """{"items": [ + {"metadata": {"name": "alice", "namespace": "saw-alice", "annotations": { + "openshell.pattern/installer-checksum": "old", "openshell.pattern/cloudinit-checksum": "c1"}}}, + {"metadata": {"name": "bob", "namespace": "saw-bob", "annotations": { + "openshell.pattern/installer-checksum": "same", "openshell.pattern/cloudinit-checksum": "c1"}}} +]}""" + + +def test_saw_restart_pending_finds_checksum_drift_without_condition(tmp_path): + """KubeVirt 1.8 does not set RestartRequired when only the template's + checksum annotations change; a stopped VM (carol) has nothing to restart.""" + env = fake_cluster(tmp_path, CHECKSUM_VMS, CHECKSUM_VMIS) + result = run_make("saw-restart-pending", env=env) + assert result.returncode == 0, result.stderr + assert "alice" in result.stdout + assert "bob" not in result.stdout and "carol" not in result.stdout + + def test_saw_restart_pending_with_nothing_pending(tmp_path): env = fake_cluster(tmp_path, '{"items": []}') result = run_make("saw-restart-pending", "CONFIRM=yes", env=env) diff --git a/tests/scripts/test_saw_restart_pending.py b/tests/scripts/test_saw_restart_pending.py new file mode 100644 index 00000000..01edce65 --- /dev/null +++ b/tests/scripts/test_saw_restart_pending.py @@ -0,0 +1,70 @@ +"""scripts/saw-restart-pending.sh against a fake `oc`: which SAW VMs wait +for a restart, and a VMI list too large to pass as one argument.""" +import json +import os +import shutil +import subprocess +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = ROOT / "scripts" / "saw-restart-pending.sh" + +pytestmark = pytest.mark.skipif(not shutil.which("jq"), reason="needs jq") + + +def vm(ns, name, checksums, restart_required=False): + return {"metadata": {"namespace": ns, "name": name}, + "spec": {"template": {"metadata": {"annotations": checksums}}}, + "status": {"conditions": [{"type": "RestartRequired", "status": "True"}] + if restart_required else []}} + + +def vmi(ns, name, checksums, padding=""): + # Running instances carry the chart's other annotations too (cloud-init, + # inputs); padding stands in for them. + return {"metadata": {"namespace": ns, "name": name, + "annotations": {**checksums, "openshell.pattern/cloud-init": padding}}} + + +def run(tmp_path, vms, vmis): + (tmp_path / "vm.json").write_text(json.dumps({"items": vms})) + (tmp_path / "vmi.json").write_text(json.dumps({"items": vmis})) + oc = tmp_path / "oc" + oc.write_text(f'#!/bin/sh\ncase "$2" in vm) cat {tmp_path}/vm.json;; vmi) cat {tmp_path}/vmi.json;; esac\n') + oc.chmod(0o755) + return subprocess.run(["bash", str(SCRIPT)], capture_output=True, text=True, timeout=60, + env={**os.environ, "PATH": f"{tmp_path}:{os.environ['PATH']}"}) + + +def test_lists_vms_with_a_restart_pending(tmp_path): + old = {"openshell.pattern/inputs-checksum": "a"} + new = {"openshell.pattern/inputs-checksum": "b"} + done = run(tmp_path, + [vm("saw-alice", "alice", new), vm("saw-bob", "bob", old), + vm("saw-carol", "carol", old, restart_required=True)], + [vmi("saw-alice", "alice", old), vmi("saw-bob", "bob", old), vmi("saw-carol", "carol", old)]) + assert done.returncode == 0, done.stderr + listed = [line.split() for line in done.stdout.splitlines() if line.startswith(" ")] + assert sorted(listed) == [["alice", "saw-alice"], ["carol", "saw-carol"]] + assert "CONFIRM=yes" in done.stdout + + +def test_a_large_vmi_list_is_not_passed_as_one_argument(tmp_path): + """Found in review: ~40 chart-derived VMIs (~200 KB) exceeded the + per-argument limit, so the script failed before listing anything.""" + old = {"openshell.pattern/inputs-checksum": "a"} + new = {"openshell.pattern/inputs-checksum": "b"} + names = [f"user{i:02d}" for i in range(40)] + vmis = [vmi(f"saw-{n}", n, old, padding="x" * 5000) for n in names] + assert len(json.dumps({"items": vmis})) > 131072, "larger than one argument may be" + done = run(tmp_path, [vm(f"saw-{n}", n, new) for n in names], vmis) + assert done.returncode == 0, done.stderr + assert sum(line.startswith(" ") for line in done.stdout.splitlines()) == 40 + + +def test_nothing_pending(tmp_path): + same = {"openshell.pattern/inputs-checksum": "a"} + done = run(tmp_path, [vm("saw-alice", "alice", same)], [vmi("saw-alice", "alice", same)]) + assert done.returncode == 0 and "No SAW VM is waiting for a restart." in done.stdout diff --git a/tests/scripts/test_vm_restart.py b/tests/scripts/test_vm_restart.py index a0f01ab9..47fe69a8 100644 --- a/tests/scripts/test_vm_restart.py +++ b/tests/scripts/test_vm_restart.py @@ -55,7 +55,7 @@ def run(restart_env, **overrides): def test_waits_through_old_missing_and_starting_instances(restart_env): result = run(restart_env) assert result.returncode == 0, result.stderr - assert Path(restart_env[1]["CALLS"]).read_text() == "sudo systemctl poweroff\n" + assert Path(restart_env[1]["CALLS"]).read_text() == "sudo systemctl poweroff --no-block\n" assert not Path(restart_env[1]["HOST_CALLS"]).exists() assert "Replacement VM saw-alice/alice is Running" in result.stdout assert "boot install/apply" in result.stdout @@ -75,7 +75,7 @@ def test_failed_guest_command_does_not_claim_restart_or_force_it(restart_env, ss assert "Replacement VM" not in result.stdout assert not Path(restart_env[1]["HOST_CALLS"]).exists() assert Path(restart_env[1]["COUNTER"]).read_text() == "1" - assert Path(restart_env[1]["CALLS"]).read_text() == "sudo systemctl poweroff\n" + assert Path(restart_env[1]["CALLS"]).read_text() == "sudo systemctl poweroff --no-block\n" def test_ssh_disconnect_during_poweroff_still_verifies_replacement(restart_env): diff --git a/values-secret.yaml.template b/values-secret.yaml.template index abd0437e..d627af4e 100644 --- a/values-secret.yaml.template +++ b/values-secret.yaml.template @@ -46,6 +46,15 @@ secrets: # # Custom keyed ports and service-CA trust are follow-up #137. # - name: api_key # path: ~/.custom-inference-api-key # may be empty for a keyless endpoint + # # Optional model settings; leave any out to keep OpenClaw's default. + # - name: thinking # off, minimal, low, medium or high + # value: high + # - name: reasoning # false: not a reasoning model, no reasoning_effort sent + # value: "false" + # - name: max_tokens # maximum output tokens + # value: "32768" + # - name: context_window # context window in tokens + # value: "128000" # Optional official APIs: enable each provider and add its name to # notebook.providers in charts/saw-bom/profiles/data-science/default.