Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions bin/lib/onboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ module.exports = {
isOpenclawReady: mod.isOpenclawReady,
arePolicyPresetsApplied: mod.arePolicyPresetsApplied,
presetsCheckboxSelector: mod.presetsCheckboxSelector,
selectPolicyTier: mod.selectPolicyTier,
selectTierPresetsAndAccess: mod.selectTierPresetsAndAccess,
setupPoliciesWithSelection: mod.setupPoliciesWithSelection,
summarizeCurlFailure: mod.summarizeCurlFailure,
summarizeProbeFailure: mod.summarizeProbeFailure,
Expand Down
81 changes: 81 additions & 0 deletions bin/lib/tiers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Tier management — load tier definitions and resolve preset selections.
//
// Tiers are defined in nemoclaw-blueprint/policies/tiers.yaml.
// Each tier is a named posture (restricted, balanced, open) that maps to
// a set of policy presets and their default access levels.
//
// The base sandbox policy is always applied regardless of tier.
// Tiers layer additional presets on top of that baseline.

const fs = require("fs");
const path = require("path");
const YAML = require("yaml");
const { ROOT } = require("./runner");

const TIERS_FILE = path.join(ROOT, "nemoclaw-blueprint", "policies", "tiers.yaml");

/**
* Load and return all tier definitions from tiers.yaml.
* Preserves the order defined in the file (restrictive → open).
*
* @returns {{ name: string, label: string, description: string, presets: Array<{name: string, access: string}> }[]}
*/
function listTiers() {
const content = fs.readFileSync(TIERS_FILE, "utf-8");
const parsed = YAML.parse(content);
return parsed.tiers;
}

/**
* Return a single tier definition by name.
* Returns null if the tier does not exist.
*
* @param {string} name
* @returns {{ name: string, label: string, description: string, presets: Array<{name: string, access: string}> } | null}
*/
function getTier(name) {
return listTiers().find((t) => t.name === name) ?? null;
}

/**
* Resolve the final preset list for a tier, applying any per-preset access
* overrides supplied by the user.
*
* overrides is a map of preset name → access level, e.g.:
* { npm: "read-write", huggingface: "read" }
*
* Presets can also be excluded by passing a `selected` allowlist — only
* presets whose names appear in the list are kept.
*
* @param {string} tierName
* @param {{ overrides?: Record<string, string>, selected?: string[] | null }} [options]
* @returns {{ name: string, access: string }[]}
*/
function resolveTierPresets(tierName, { overrides = {}, selected = null } = {}) {
const tier = getTier(tierName);
if (!tier) {
throw new Error(`Unknown tier: ${tierName}`);
}

let presets = tier.presets.map((p) => ({
name: p.name,
access: overrides[p.name] ?? p.access,
}));

if (selected !== null) {
const allowSet = new Set(selected);
presets = presets.filter((p) => allowSet.has(p.name));
}

return presets;
}

module.exports = {
TIERS_FILE,
listTiers,
getTier,
resolveTierPresets,
};
43 changes: 43 additions & 0 deletions nemoclaw-blueprint/policies/tiers.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Tier definitions for the NemoClaw policy selector.
#
# Each tier maps to a named posture. The base sandbox policy
# (openclaw-sandbox.yaml) is always applied regardless of tier.
# Tiers add presets on top of that baseline.
#
# access values:
# read — GET only (or equivalent read-only rules for that service)
# read-write — GET + POST/PUT/PATCH (explicitly opt-in; never the default)

tiers:
- name: restricted
label: Restricted
description: Base sandbox only. No third-party network access beyond inference and core agent tooling.
presets: []

- name: balanced
label: Balanced
description: Full dev tooling and web search. Package installs, model downloads, and inference. No messaging platform access.
presets:
- { name: npm, access: read-write }
- { name: pypi, access: read-write }
- { name: huggingface, access: read-write }
- { name: brew, access: read-write }
- { name: brave, access: read-write }

- name: open
label: Open
description: Broad access across third-party services including messaging and productivity. User accepts responsibility for the expanded scope.
presets:
- { name: npm, access: read-write }
- { name: pypi, access: read-write }
- { name: huggingface, access: read-write }
- { name: brew, access: read-write }
- { name: brave, access: read-write }
- { name: slack, access: read-write }
- { name: discord, access: read-write }
- { name: telegram, access: read-write }
- { name: jira, access: read-write }
- { name: outlook, access: read-write }
57 changes: 57 additions & 0 deletions scripts/dev-tier-selector.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// DEV SCRIPT — NOT FOR PRODUCTION USE
//
// Manual smoke-test for the interactive tier selector and preset access-mode UI.
// Stubs out heavy I/O (openshell, registry, credentials) so the TUI can be exercised
// without a real NemoClaw installation.
//
// Usage:
// node scripts/dev-tier-selector.js
//
// This script is intentionally not part of the vitest suite. For automated coverage
// of this flow see test/policy-tiers-onboard.test.js.

"use strict";

const readline = require("readline");

// ── Stubs ──────────────────────────────────────────────────────────────────
const creds = require("../bin/lib/credentials.js");
const runner = require("../bin/lib/runner.js");
const registry = require("../bin/lib/registry.js");

creds.ensureApiKey = async () => {};
creds.getCredential = () => null;
creds.prompt = (msg) =>
new Promise((resolve) => {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.question(msg, (answer) => {
rl.close();
resolve(answer);
});
});

runner.run = () => {};
runner.runCapture = () => "";

registry.getSandbox = () => ({ name: "test-sb", model: null, provider: null });
registry.registerSandbox = () => true;
registry.updateSandbox = () => true;

// ── Run ────────────────────────────────────────────────────────────────────
const { selectPolicyTier, selectTierPresetsAndAccess } = require("../bin/lib/onboard.js");
const policies = require("../bin/lib/policies.js");

(async () => {
const tier = await selectPolicyTier();
console.log("\nSelected tier:", tier);

const allPresets = policies.listPresets();
const resolved = await selectTierPresetsAndAccess(tier, allPresets);
console.log("\nResolved presets:", resolved);
})().catch((err) => {
console.error(err);
process.exit(1);
});
23 changes: 19 additions & 4 deletions src/lib/model-prompts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ export interface ModelPromptOptions {
cloudModelOptions?: Array<{ id: string; label: string }>;
remoteModelOptions?: Record<string, string[]>;
backToSelection?: string;
/** Pre-fill this model ID as the default in interactive prompts. */
defaultModelId?: string;
}

function getNavigationChoice(value = ""): "back" | "exit" | null {
Expand Down Expand Up @@ -119,6 +121,14 @@ export async function promptManualModelId(

export async function promptCloudModel(options: ModelPromptOptions = {}): Promise<string> {
const deps = resolvePromptOptions(options);
const defaultModelId = options.defaultModelId ?? "";

// Find if the default matches a curated option
const defaultCuratedIdx = defaultModelId
? deps.cloudModelOptions.findIndex((o) => o.id === defaultModelId)
: -1;
// Default list selection: match defaultModelId, or fall back to first option (index 0)
const defaultListChoice = defaultCuratedIdx >= 0 ? defaultCuratedIdx + 1 : 1;

deps.writeLine("");
deps.writeLine(" Cloud models:");
Expand All @@ -128,15 +138,15 @@ export async function promptCloudModel(options: ModelPromptOptions = {}): Promis
deps.writeLine(` ${deps.cloudModelOptions.length + 1}) Other...`);
deps.writeLine("");

const choice = await deps.promptFn(" Choose model [1]: ");
const choice = await deps.promptFn(` Choose model [${defaultListChoice}]: `);
const navigation = deps.getNavigationChoiceFn(choice);
if (navigation === "back") {
return deps.backToSelection;
}
if (navigation === "exit") {
deps.exitFn();
}
const index = parseInt(choice || "1", 10) - 1;
const index = parseInt(choice || String(defaultListChoice), 10) - 1;
if (Number.isFinite(index) && index >= 0 && index < deps.cloudModelOptions.length) {
return deps.cloudModelOptions[index].id;
}
Expand All @@ -147,11 +157,16 @@ export async function promptCloudModel(options: ModelPromptOptions = {}): Promis
return deps.backToSelection;
}

// If default is a custom (non-curated) model ID, pre-fill it in the manual prompt
const manualDefault = defaultCuratedIdx < 0 && defaultModelId ? defaultModelId : "";
const manualLabel = manualDefault
? ` NVIDIA Endpoints model id [${manualDefault}]: `
: " NVIDIA Endpoints model id: ";
return promptManualModelId(
" NVIDIA Endpoints model id: ",
manualLabel,
"NVIDIA Endpoints",
(model) => deps.validateNvidiaEndpointModelFn(model, nvidiaApiKey),
deps,
{ ...deps, promptFn: async (q) => (await deps.promptFn(q)) || manualDefault },
);
Comment on lines +160 to 170

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Guard manual default fallback with model-id safety checks.

When defaultModelId is invalid and non-curated, the fallback promptFn can repeatedly return that invalid default, causing an endless validation loop.

💡 Proposed fix
-  const manualDefault = defaultCuratedIdx < 0 && defaultModelId ? defaultModelId : "";
+  const safeDefaultModelId = isSafeModelId(defaultModelId) ? defaultModelId : "";
+  const manualDefault = defaultCuratedIdx < 0 ? safeDefaultModelId : "";
   const manualLabel = manualDefault
     ? `  NVIDIA Endpoints model id [${manualDefault}]: `
     : "  NVIDIA Endpoints model id: ";
   return promptManualModelId(
     manualLabel,
     "NVIDIA Endpoints",
     (model) => deps.validateNvidiaEndpointModelFn(model, nvidiaApiKey),
-    { ...deps, promptFn: async (q) => (await deps.promptFn(q)) || manualDefault },
+    {
+      ...deps,
+      promptFn: async (q) => {
+        const answer = await deps.promptFn(q);
+        return answer || manualDefault;
+      },
+    },
   );
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/model-prompts.ts` around lines 160 - 170, The current fallback uses
manualDefault directly in the promptFn, which can cause an endless validation
loop if defaultModelId is invalid; update the logic around
manualDefault/promptFn so the fallback is only returned after verifying it with
deps.validateNvidiaEndpointModelFn(manualDefault, nvidiaApiKey) (or run that
validation once when computing manualDefault/defaultCuratedIdx), and otherwise
return an empty string (or no fallback) so promptManualModelId can re-prompt;
ensure references to manualDefault, promptManualModelId, deps.promptFn,
deps.validateNvidiaEndpointModelFn, defaultModelId and defaultCuratedIdx are
used to locate and implement this guard.

}

Expand Down
Loading